I have a weird issue with regards to getline while reading from file.
Below is the code.
#include <fstream>
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
struct call {
string l;
string k;
};
int main () {
ifstream read;
string fn = "in.txt";
string temp;
call mc;
vector<call> vcall;
read.open (fn.c_str ());
while (getline (read, temp)) {
temp.erase (temp.end () - 1);
if (temp.substr (0,1).compare ("L") == 0) {
temp = temp.substr (7);
stringstream ss (temp);
while (ss) {
getline (ss, mc.l, ':');
getline (ss, mc.k, ':');
vcall.push_back (mc);
}
}
}
for (int i = 0; i < vcall.size (); i++) {
cout << vcall [i].i << vcall [i].k << endl;
}
}
The text file in.txt contains a line.
Los:0:A:1:B:2:C:3:D:4:E:
The output from the program gives me.
0A
1B
2C
3D
4E
4E
Not sure why is it so. It should not have the last (another) 4 in the output.
I’ve tried re-creating the textfile, re-writing the codes in another file and compile.
Tried in Ubuntu (g++), and Windows (mingw) and still having the same issue.
Update:
The reason why I didn’t use while (getline (ss, mc.l, ‘:’)) is because I need multiple part. I made a slight changes to the code above, with structure having 2 string to store.
Also made changes to my text file to reflect the changes.
So how can I do it? Thanks.
Change this:
To this:
The problem is that you don’t check if the read fails until you’ve already added the item to the vector. So when the last read fails, the item, which remains unchanged from the previous call to getline, gets pushed back onto the vector again. The modified version bails out as soon as the read fails. You used this idiom in your primary for loop, the one that reads lines from the file. So I wonder why you didn’t use it with the stringstream.
In response to the update:
If you find the condition in your while statement getting too unwieldy, you can always do something like this: