Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read groups of integers from a file, line by line in C++

Tags:

c++

input

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
like image 627
Peter Smit Avatar asked Feb 18 '10 08:02

Peter Smit


People also ask

How to read lines of text file in C?

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().

Does fgets read line by line?

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.


2 Answers

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>() ) );
   }
}
like image 59
David Rodríguez - dribeas Avatar answered Sep 19 '22 14:09

David Rodríguez - dribeas


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();
}
like image 43
synepis Avatar answered Sep 20 '22 14:09

synepis