I am reading .csv file lines via :
vector <string> vec_str;
char line[40];
while (1) {
memset (line, 0, 40 * sizeof (char));
if (fgets (line, 0, f_str_csv) == NULL) {
break;
}
//and then making strings out of NL trimmed line, and storing them in vec_str as
vec_str.push_back (string (line, strlen (line)).substr (0, strlen (line) - 1));
}
I do not seem to be able to get rid of carriage return at the end of line
read from the csv file.
This becomes apparent when I parse the string thru strtok
and sscanf
via:
vector <string>::iterator vec_str_it = vec_str.begin ();
strncpy (line, (*vec_str_it).c_str (), (*vec_str_it).length ());
char *buffer = NULL;
int data[2], i = 0;
char str[10];
buffer = strtok (line, ",");
while (buffer != NULL) {
cout << "[" << buffer << "]" << endl;
if (i == 2)
sscanf (buffer, "%s", str);
else
sscanf (buffer, "%d", &data[i]);
buffer = NULL;
buffer = strtok (NULL, ",");
i++;
}
gives me an output:
[10]
[20]
[James K.
]
for the input 10,20,James K.
which is the line I read from the csv file.
What is happening wrong here?
Edit:
Also for later files, if a smaller name happens at the end of the line, like 11,31,Wu S.
after the James K.
line, I get remnants of James K.
in the buffer
after 2nd iteration as is obvious from result as :
[11]
[31]
[Wu S.
K.
]
Someone please tell me how to avoid this misbehaviour of carriage returns.