0

I have the following code lines :

printf("enter a number: \n");
if (scanf("%d", &x) == 1)
{ //do some stuff}
else {return 1;}
printf("enter another number: \n");
if (scanf("%d",&y) == 1)
{ //do some stuff}
else {return 1;}

the code works but when I'm putting an input to x in the following form "1 1" (1 then space then 1 again) it put the 2nd 1 into y. How can I make it won't happen? it should just stop the code.

I know there are other methods to get inputs but as for now, I'm only allowed to use scanf to get input from the user.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Then... just stop the code. – user202729 Mar 23 '18 at 00:53
  • Possible duplicate of [How do you allow spaces to be entered using scanf?](https://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf) or [Reading string from input with space character?](https://stackoverflow.com/questions/6282198/reading-string-from-input-with-space-character). – CRM Mar 23 '18 at 01:01

1 Answers1

0

You are seeing the normal behaviour of scanf. The second 1 is read by the second scanf because %d skips white spaces until it finds the next number to convert.

After the first scanf this is what is left in the input buffer

+-----+-----+------+
| ' ' | '1' | '\n' |
+-----+-----+------+

So if you want to stop after the first conversion, you need to clear the buffer. You can use this function for this:

void clear_line(FILE *fp)
{
    if(fp == NULL)
        return;

    int c;
    while((c = fgetc(fp)) != '\n' && c != EOF);
}

Then you can do this:

printf("enter a number: \n");
if (scanf("%d", &x) == 1)
{ //do some stuff}
else {return 1;}

clear_line(stdin);

printf("enter another number: \n");
if (scanf("%d",&y) == 1)
{ //do some stuff}
else {return 1;}

clear_line(stdin);

In this case even if you enter 1 1, the second scanf will wait for user input.

Pablo
  • 13,271
  • 4
  • 39
  • 59
  • To be clear, the function `clear_file_buffer` only **read and ignore** from the `FILE *fp` only until the end of the line or end of file. – user202729 Mar 23 '18 at 00:55
  • Yes, perhaps I should rename the function to make it more clear – Pablo Mar 23 '18 at 00:56