ifstream help needed.
Hey,
Could someone show me how I would use ifstream to get, lets say the 1st line and the 3rd line of a file? Thanks.
To read a line, you can use ifstream::getline(char* s, streamsize n, char delim=''\n''). This will extract characters from a stream, and store them in a buffer pointed to by s. Characters are extracted until either (n - 1) characters have been extracted, the delimiter is found, or if the end of file or any error occurs in the input sequence. If the delimiter is found, it is extracted but not stored. An ending null character is automatically appended after the data stored in s.
You can use ifstream::ignore(streamsize n=1, int delim=EOF) to extract and discards characters from an input stream. Extraction ends when n characters have been discarded or when delim is found, whichever comes first. In the last case, delim is also extracted. You can use ignore(std::INT_MAX, ''\n'') to the next line (INT_MAX is defined in the climits header file).
You can also read a line into a string: use the (global) function getline(istream& is, string& s) for that.
If you want to go to a specific line number, a solution is to go to the beginning of the file, and then do ignore(INT_MAX, ''\n'') until you''re at the correct line number.
HTH
You can use ifstream::ignore(streamsize n=1, int delim=EOF) to extract and discards characters from an input stream. Extraction ends when n characters have been discarded or when delim is found, whichever comes first. In the last case, delim is also extracted. You can use ignore(std::INT_MAX, ''\n'') to the next line (INT_MAX is defined in the climits header file).
You can also read a line into a string: use the (global) function getline(istream& is, string& s) for that.
If you want to go to a specific line number, a solution is to go to the beginning of the file, and then do ignore(INT_MAX, ''\n'') until you''re at the correct line number.
HTH
Some useful C++ links:Free multiplatform ANSI C++ Standard Library implementationVisual C++ 6.0 STL fixesVisual C++ 6.0 noncompliance issuesC++ FAQ Lite
Another good way is to use structures, then you can read in the structure, pull it out, test for a value, whatever.
If you are extemely organized (like i try to be :D) you can know exactly the order of what is in the file, thus you can move forward the sizeof(whatever)
"You call him Dr. Grip, doll!"
If you are extemely organized (like i try to be :D) you can know exactly the order of what is in the file, thus you can move forward the sizeof(whatever)
"You call him Dr. Grip, doll!"
"You call him Dr. Grip, doll!"
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement