I have a text file with on every line one or more integers, seperated by a space. How can I in an elegant way read this with C++? If I would not care about the lines I could use cin >>, but it matters on which line integers are.
Example input:
1213 153 15 155
84 866 89 48
12
12 12 58
12
Steps To Read A File:Open a file using the function fopen() and store the reference of the file in a FILE pointer. Read contents of the file using any of these functions fgetc(), fgets(), fscanf(), or fread(). File close the file using the function fclose().
The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.
It depends on whether you want to do it in a line by line basis or as a full set. For the whole file into a vector of integers:
int main() {
std::vector<int> v( std::istream_iterator<int>(std::cin),
std::istream_iterator<int>() );
}
If you want to deal in a line per line basis:
int main()
{
std::string line;
std::vector< std::vector<int> > all_integers;
while ( getline( std::cin, line ) ) {
std::istringstream is( line );
all_integers.push_back(
std::vector<int>( std::istream_iterator<int>(is),
std::istream_iterator<int>() ) );
}
}
You could do smtng like this(I used cin, but you can use any other file stream):
string line;
while( getline( cin, line ) )
{
istringstream iss( line );
int number;
while( iss >> number )
do_smtng_with_number();
}
Or:
int number;
while( cin >> number )
{
do_smtng_with_number();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With