I have the code below. The code is followed by a sample input file. When I go to cout the arrays it does it like this:
Output:
Joe
Browns
93
Samantha
Roberts
45
Why is the string only reading until the white-space and then moving on? I thought string accepts white-space? Thanks.
Code:
ifstream in_stream;
in_stream.open("in.dat");
if(in_stream.fail())
{
cout<< "Input file opening failed. \n";
exit(1);
}
vector <string> a;
int i = 0;
string dummy;
while(in_stream>>dummy)
{
a.push_back(dummy);
cout<<a[i]<<endl;
i++;
}
in_stream.close( );
Sample Input File:
Joe Browns
93
Samantha Roberts
45
operator>>
interprets any kind of whitespace as a delimiter. Use getline()
if you need to read entire lines.
Change the while loop so you read the whole line.
while (getline(in_stream, dummy))
{
a.push_back(dummy);
cout << a[i] << endl;
i++;
}
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.