c - found extra whitespace while using fscanf -
i have file:
hello:12312 bye:333 hey:22 so read using fscanf
file *file = fopen( argv[1], "r" ); if ( file == 0 ) { printf( "could not open file\n" ); } else { while(fscanf(file, "%[^:]:%d", word, &integer) != eof) { printf("word: %s, integer: %d\n", word, integer); } fclose( file ); } and got:
word: hello, integer: 12312 word: bye, integer: 333 word: hey, integer: 22 so apparently there whitespace except first word, why happening?
from fscanf():
all conversion specifiers other [, c, , n consume , discard leading whitespace characters before attempting parse input.
and \n remain input stream after "%d".
to correct add leading space format speicifer skip whitespace:
while(fscanf(file, " %[^:]:%d", word, &integer) == 2) { } changed != eof == 2 prevent accepting lines of format "hello:" or "hello".
Comments
Post a Comment