Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file line by line using ifstream in C++

The contents of file.txt are:

5 3 6 4 7 1 10 5 11 6 12 3 12 4 

Where 5 3 is a coordinate pair. How do I process this data line by line in C++?

I am able to get the first line, but how do I get the next line of the file?

ifstream myfile; myfile.open ("file.txt"); 
like image 896
dukevin Avatar asked Oct 23 '11 20:10

dukevin


People also ask

How do you read a line of text from a file in C++?

In C++, you may open a input stream on the file and use the std::getline() function from the <string> to read content line by line into a std::string and process them. std::ifstream file("input. txt"); std::string str; while (std::getline(file, str)) { // process string ... }

How do you read each line in a file C?

The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be. You can find all the code examples and the input file at the GitHub repo for this article.


1 Answers

First, make an ifstream:

#include <fstream> std::ifstream infile("thefile.txt"); 

The two standard methods are:

  1. Assume that every line consists of two numbers and read token by token:

    int a, b; while (infile >> a >> b) {     // process pair (a,b) } 
  2. Line-based parsing, using string streams:

    #include <sstream> #include <string>  std::string line; while (std::getline(infile, line)) {     std::istringstream iss(line);     int a, b;     if (!(iss >> a >> b)) { break; } // error      // process pair (a,b) } 

You shouldn't mix (1) and (2), since the token-based parsing doesn't gobble up newlines, so you may end up with spurious empty lines if you use getline() after token-based extraction got you to the end of a line already.

like image 64
Kerrek SB Avatar answered Sep 21 '22 07:09

Kerrek SB