0

I am trying to accept input from a file. This file is in the format of an integer, followed by a tab, followed by a string (which may or may not have spaces).

for example:

1\tls -l
2\tls

I tried using:

int   cmd_num;
char command[80];

while (fscanf(ifp, "%d\t%s", &cmd_num, command) != EOF) {
    ...
}

However, this failed when it saw a space. Any help?

phuclv
  • 37,963
  • 15
  • 156
  • 475
user1742385
  • 63
  • 1
  • 1
  • 4
  • I didn't understand _this failed when it saw a space_ is it reading 1\tls – Bhavik Shah Nov 02 '12 at 05:06
  • This works when none of the strings had spaces. However, when a string had a space it went into an infinite loop. – user1742385 Nov 02 '12 at 05:07
  • can you post a failing file input? – Bhavik Shah Nov 02 '12 at 05:09
  • So if I had this in the loop "printf("%d\t%s\n", cmd_num, command);" it would output the line "1\tls\n" to infinity. – user1742385 Nov 02 '12 at 05:10
  • ***To those voting to close*** — This is a frequently encountered problem and is not too localized. If you can find a duplicate (I'm sure there are some), then by all means close it as a duplicate. But it is not too localized. – Jonathan Leffler Nov 02 '12 at 05:25
  • 1
    Possible duplicates include: [C `scanf` with spaces problem](http://stackoverflow.com/questions/4358383/c-scanf-with-spaces-problem), [How do you allow spaces to be entered using `scanf`?](http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf), and [Reading string with spaces using `scanf()`](http://stackoverflow.com/questions/9306303/reading-string-with-spaces-using-scanf). The earliest of these is SO 1247989 and should probably be given precedence. I doubt this list is exhaustive. – Jonathan Leffler Nov 02 '12 at 05:37

2 Answers2

1

You probably need to use a scan-set to read the string:

if (fscanf(fp, "%d\t%79[^\n]\n", &cmd_num, command) != 2)
    ...error handling...
else
    ...use cmd_num and command...

Note the size constraint in the format string to prevent buffer overflow.

Note, too, that you will not know whether the newline is matched. You might be better off using fgets() to read the whole line (or getline()), and then using sscanf() instead of fscanf(); at least you'll know whether the newline was collected (and can gobble to the newline if necessary).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Try this in your fscanf function:

fscanf(fp,"%d\t%[^\n]s",&cmd_num,command);

This will surely work...

phuclv
  • 37,963
  • 15
  • 156
  • 475
m4n1c
  • 127
  • 8
  • You don't need the `s` with a scan-set. Mind you, it would not actually cause problems, but that's only because it is after the last conversion in the format string and you can't detect when there are mismatches there. – Jonathan Leffler Nov 02 '12 at 06:53