BinaryX
BinaryX

Reputation: 37

C - sscanf not ignoring white space

I am reading in a text file and using a comma as a delimiter, the line below does work however when I print out lname it does not ignore the white space after the comma and prints a space before name. How can I adjust the code to ignore white space?

example of text:

Rob, Smith, 4, 12, sometext
Steve, Jones, 41, 286, sometext

sscanf(line, "%[^,],%[^,],%d,%d,%s", fname,lname,&num1,&num2,info);

Upvotes: 1

Views: 2936

Answers (1)

Spikatrix
Spikatrix

Reputation: 20244

Just add a whitespace character if you want to ignore whitespace:

sscanf(line, " %[^,], %[^,], %d, %d, %s", fname, lname, &num1, &num2, info);

The space before %d and %s are not required as they already skip leading whitespace characters. The only format specifiers which does not skip leading whitespace are %c, %[ and %n.

Note that a whitespace character in the format string of *scanf instructs scanf to scan any number of whitespace, including none, until the first non-whitespace character.

Upvotes: 6

Related Questions