First of all, please understand that I'm learning c++ and I am a new bee. I tried to read the comma separated lines from a file. Mostly it looks okay, but I realized that numbers were mixed up.
As you can see, output line 4, 6, 7, and 9 have their first two numbers (1 and 0) messed up/ misplaced. Much appreciated!
people.txt
0,0,Person,One,16.1
1,1,Person,Two,5
1,1,Person,Three,12
0,1,Person,Four,.2
0,0,Person,Five,10.2
0,1,Person,Six,.3
1,0,Person,Seven,12.3
1,1,Person,Eight,4.2
1,0,Person,Nine,16.4
1,1,Person,Ten,1.4
c++ output:
1
0,0,Person,One,16.1
0,0,Person,One,16.1
2
1,1,Person,Two,5
1,1,Person,Two,5
3
1,1,Person,Three,12
1,1,Person,Three,12
4
1,0,Person,Four,.2
0,1,Person,Four,.2
5
0,0,Person,Five,10.2
0,0,Person,Five,10.2
6
1,0,Person,Six,.3
0,1,Person,Six,.3
7
0,1,Person,Seven,12.3
1,0,Person,Seven,12.3
8
1,1,Person,Eight,4.2
1,1,Person,Eight,4.2
9
0,1,Person,Nine,16.4
1,0,Person,Nine,16.4
10
1,1,Person,Ten,1.4
1,1,Person,Ten,1.4
My code to read them is:
ifstream ifs;
string filename = "people.txt";
ifs.open(filename.c_str());
int lineCount = 1;
while(!ifs.eof()){
int num1, num2;
string num1Str, num2Str, num3Str, first, last, line;
float num3;
getline(ifs, line);
stringstream ss(line);
getline(ss, num1Str, ',');
getline(ss, num2Str, ',');
getline(ss, first, ',');
getline(ss, last, ',');
getline(ss, num3Str);
num1 = stoi(num1Str);
num2 = stoi(num2Str);
num3 = atof(num3Str);
cout <<lineCount<<endl<< num1 << "," << num2 << ","
<< first << "," << last <<"," << num3
<< "\n\t" << line << endl << endl;
lineCount++;
}
Not sure exactly what was going on because it shouldn't even compile. You are using std::atof
(takes in a char*
) instead of std::stof
(takes in a std::string
).
Also, the link from Fei Xiang indicates you shouldn't use eof()
at all in this situation; you should use:
while (std::getline(ifs, line)) {
// use line
}
After those fixes, it seems to work fine: ideone example using cin
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.