Search code examples
c++ifstreamstrtok

strtok is using wrong delimiter (space as well as ",")


Is there a way to make strtok() not interpret spaces as separators? I'm reading from .csv file, and my code has:

ifstream inf("file.csv");
char *n, *a, *b;
char n1[80], a1[80], b1[80], temp[80];
inf >> temp;
n = strtok(temp, ",");
strcpy(n1, n);
a = strtok(NULL, ",");
strcpy(a1, a);
b = strtok(NULL, ",");
strcpy(b1, b);
cout << a1 << " " << b1 << endl;

File contents:

123,San Francisco, Los Angeles

I think strtok interprets space as '\n' but I don't know how to ignore it. I tried putting inf.ignore(' ') but doesn't work and gives me some random values. If, however, I change my file to 123,San_Francisco, Los_Angeles then the program works. How could I ignore spaces?


Solution

  • Don't blame strtok, its ifstream which stops extracting when finding a whitespace character. You should use one of the getline() variants if you want to read an entire line.