How do you count lines in a file? And how do you read to the different lines? I know this question has been asked before but I never found a straight answer.
How do you count lines in a file? And how do you read to the different lines? I know this question has been asked before but I never found a straight answer.
hope this helps:
Code:#include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream read; // create our stream string content; // create a string to hold the content of the file read.open("file.ext"); // open the file (make sure it exists) while(read >> content) // create a while loop to read the file { cout << content; // print the file's contents } read.close(); // close the file return 0; }
I am against the teaching of evolution in schools. I am also against widespread
literacy and the refrigeration of food.
There are several solutions. You can read in every line and keep count. Another solution is to read in raw data and find "\n."
Kuphryn
your code doesn't quite make since, abrege, i think read and content are the same things... but i'm not sure.
Code:ifstream infile; infile.open("SomeTextfile.txt"); int lines=0; string strLine; if(infile.good()) { while(!infile.eof() && infile.good()) { getline(infile,strLine); lines++; } } infile.close();
It's like what kuphryn said, loop until you reach '\n' and that's a line, make a counter to keep track of the number of '\n's, and that's it...
does this answer your question.
Hi, I think this should help:
I just learnt this stuff from Bruce Eckels Thinking in C++Code://using vectors to open file and count lines #include<iostream> #include<fstream> #include<string> #include<vector> int main() { vector<string> v; string line; ifstream in("something"); int i; int count=0; while(in.getline(in, line)) v.push_back(line); for(int i=0; i<v.size(); i++){ cout << v[i] << endl; count += i; } cout << "Total lines: " << count; return 0; }
I hope it helped.
"Cut the foreplay and just ask, man."