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?

6
  • I didn't understand this failed when it saw a space is it reading 1\tls Commented Nov 2, 2012 at 5:06
  • This works when none of the strings had spaces. However, when a string had a space it went into an infinite loop. Commented Nov 2, 2012 at 5:07
  • can you post a failing file input? Commented Nov 2, 2012 at 5: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. Commented Nov 2, 2012 at 5:10
  • 1
    Possible duplicates include: C scanf with spaces problem, How do you allow spaces to be entered using scanf?, and 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. Commented Nov 2, 2012 at 5:37

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

Try this in your fscanf function:

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

This will surely work...

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.