Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line by line reading in C and C++?

Tags:

c++

c

line

I want to read line by line from a file in C or C++, and I know how to do that when I assume some fixed size of a line, but is there a simple way to somehow calculate or get the exact size needed for a line or all lines in file? (Reading word by word until newline is also good for me if anyone can do it that way.)

like image 304
mushroom Avatar asked Apr 08 '11 15:04

mushroom


1 Answers

If you use a streamed reader, all this will be hidden from you. See getline. The example below is based from the code here.

// getline with strings
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string str;
  ifstream ifs("data.txt");
  getline (ifs,str);
  cout << "first line of the file is " << str << ".\n";
}
like image 97
Jeff Foster Avatar answered Oct 05 '22 10:10

Jeff Foster