Reputation: 11
I can't understand why this code is not working properly:
#include<stdio.h>
int main()
{
char string [100];
int a;
printf(">");
scanf("%d", &a);
printf(">");
gets(string);
printf("%s\n", string);
}
This is a little part from a program that I had to build and I can't understand why after getting the value into a by scanf() function, the program just skip or not reading properly the string by gets() function. If you copy the code into compiler and tries to run you will understand what I mean.
Upvotes: 1
Views: 340
Reputation: 41
Whenever you need to read a sentence composed with spaces (after any scanf's), modify your the scanf to:
scanf(" [^\n]", mystring);
^ Space here.
Look your example:
#include<stdio.h>
int main(void)
{
char mystring[100];
int a;
printf(">");
scanf("%d", &a);
printf(">");
scanf(" %[^\n]", mystring);
printf("Number:%d\nString: %s\n", a, mystring);
return 0;
}
Upvotes: 0
Reputation: 182649
The %d
specifier doesn't eat the newline (or other blanks for that matter). Try this:
scanf("%d ", &a);
^
That space makes scanf
throw away all the blanks until a non-blank. Incidentally, your question is remarcably similar to this C FAQ.
gets
, it's so bad it's not even in the language anymore.
Use fgets
insteadfflush(stdin)
for your problemUpvotes: 3