why does vector.size() read in one line too little?
Posted
by ace
on Stack Overflow
See other posts from Stack Overflow
or by ace
Published on 2010-04-22T21:28:01Z
Indexed on
2010/04/22
21:33 UTC
Read the original article
Hit count: 164
when running the following code, the amount of lines will read on less then there actually is (if the input file is main itself, or otherwise) why is this and how can i change that fact (besides for just adding 1)?
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// open text file for input
string file_name;
cout << "please enter file name: ";
cin >> file_name;
// associate the input file stream with a text file
ifstream infile(file_name.c_str());
// error checking for a valid filename
if ( !infile ) {
cerr << "Unable to open file "
<< file_name << " -- quitting!\n";
return( -1 );
}
else cout << "\n";
// some data structures to perform the function
vector<string> lines_of_text;
string textline;
// read in text file, line by line
while (getline( infile, textline, '\n' )) {
// add the new element to the vector
lines_of_text.push_back( textline );
// print the 'back' vector element - see the STL documentation
cout << "line read: " << lines_of_text.back() << "\n";
}
cout<<lines_of_text.size();
return 0;
}
© Stack Overflow or respective owner