Reputation: 47
I'm trying this:
int M,N,K;
printf("Enter (m,k,n) : ");
scanf("%d %d %d ", &M, &K, &N);
printf("\nDone?");
This is inside the main function. I need the program to read the three integers but when I run it, it just reads the three but doesn't go past the scanf, i.e. "Done?" isn't executed, as if it's still waiting for more input. If I remove the space after the last %d, it works fine. But why is that so?
Upvotes: 3
Views: 227
Reputation: 154228
If I remove the space after the last %d, it works fine. But why is that so?
" "
in "%d %d %d "
directs scanf()
to read, and not save, any number of whites-spaces including '\n'
.
scanf()
keeps consuming white-spaces until some non-white-space in encountered. @user3121023
"%d %d %d "
obliges scanf()
to not return until some non-white-space is read after the 3 numbers.
Tip: Avoid scanf()
. Use fgets()
and then parse the string. @DevSolar
Upvotes: 5
Reputation: 1127
Try to read the values separately. I don't think that scanf is intended to be used this way. Also, what you're expecting putting a blank space at the end of scanf's string? Try this:
scanf("%d", &M);
scanf("%d", &K);
scanf("%d", &N);
EDIT: I checked it out, and yeah, you can do that. But why you would want to do that way? It will be harder to validate if the user input is incorrect, like with a blank space or a non intended char.
You could read this as a full string with fgets()
and the tokenize it with strtok()
, if you're expecting everything in a single text line.
Or simply read the values separately as showed.
Well, just my opinion, tho. If I'm wrong, please someone clarify me.
Upvotes: 0
Reputation: 1415
Here is the way to take user inputs in multiple variables:
int M,N,K;
printf("Enter (m,k,n) : ");
scanf("%d", &M);
scanf("%d", &N);
scanf("%d", &K);
printf("\nDone?");
Upvotes: 0