简体   繁体   中英

C++: Getline stops reading at first whitespace

Basically my issue is that I'm trying to read in data from a .txt file that's full of numbers and comments and store each line into a string vector, but my getline function stops reading at the first whitespace character so a comment like (* comment *) gets broken up into

str[0] = "(*";
str[1] = "comment";
str[2] = "*)";

This is what my codeblock for the getline function looks like:

int main() {
string line;
string fileName;
cout << "Enter the name of the file to be read: ";
cin >> fileName;

ifstream inFile{fileName};

istream_iterator<string> infile_begin {inFile};
istream_iterator<string> eof{};
vector<string> data {infile_begin, eof};
while (getline(inFile, line))
{
    data.push_back(line);
}

And this is what the .txt file looks like:

101481
10974
1013
(* comment *) 0
28292
35040
35372
0000
7155
7284
96110
26175

I can't figure out why it's not reading the whole line.

This is for the very simple reason that your code is not using std::getline to read the input file.

If you look at your code very carefully, you will see that before you even get to that point, your code constructs an istream_iterator<string> on the file, and by passing it, and the ending istream_iterator<string> value to the vector 's constructor, this effectively swallows the entire file, one whitespace-delimited word at a time, into the vector.

And by the time things get around to the getline loop, the entire file has already been read, and the loop does absolutely nothing. Your getline isn't really doing anything, with the current state of affairs.

Get rid of that stuff that involves istream_iterator s, completely, and simply let getline do the job it was intended for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM