0

I have a code here which has some unwanted behaviour when inputting strings with spaces. eg print illegal_argument. When an input with multiple words comes in I would like it to only register the first word.

What currently happens is:

christian@oblig2 $ print 0
Enter router ID for information > ID: 0, flag: f7, model_length: 13, model: D-Link y6000

It registers the first print for the comparison in the command-loop. But instead of scanf prompting the user for the next input, it instead ignores that and takes the second word/number input by the user from the previous scanf.

What I want to happen is:

christian@oblig2 $ print 0
Enter router ID for information > 0
ID: 0, flag: f7, model_length: 13, model: D-link y6000.

Everything works as intended otherwise, but I wonder if there's a simpler way to do this. I've tried using Strtok, without much luck.

char input[256];
printf("%s@oblig2 $ ", getenv("USER"));
scanf("%s", input);

if(strcmp(input, "print") == 0) {
    print();
}

The above code is how I get input from the user.

Anyone got any ideas?

  • 2
    When you want the whole input line, don't use `scanf`, use `fgets` instead. – Olaf Dietsche Oct 03 '16 at 20:53
  • @OlafDietsche Trying `fgets(input, 256, stdin)` doesn't work, unless I'm doing something wrong. Trying `$ print` produces `: command not found.`. – Christian M Oct 03 '16 at 21:02
  • @Christian S `fgets(input, 256, stdin)` works. Other things in code need to change too. See http://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input – chux - Reinstate Monica Oct 03 '16 at 21:49

1 Answers1

2

After the scanf() takes the first input value, it leaves the rest in the input stream. Try this to discard the remaining characters:

int ch;
while ((ch = getchar()) != '\n' && ch != EOF)
    continue;             // discard remaining characters

If you put these lines before the next read from stdin, the extra characters won't corrupt your input.

ad absurdum
  • 19,498
  • 5
  • 37
  • 60