Even though I use this condition in scanf("[^\n]s", x)
, or "%34[^\n]"
, or %127s
, I'm unable to get answers correctly. Is there any problem with the scanf
area or in some other part....
#include <stdio.h>
int main()
{
int i = 4;
double d = 4.0;
char s[] = "hello ";
int a;
double b;
unsigned char string_2[100];
scanf("%d",&a);
scanf("%lf",&b);
scanf("%[^\n]s",string_2);
printf("%d",a+i);
printf("\n%lf",d+b);
printf("\n%s",s);
printf("%s",string_2);
return(0);
}
Don't use scanf
like that.
In this:
scanf("%lf",&b);
scanf("%[^\n]s",string_2);
The first scanf
reads a number from the input, but has to wait for your terminal to give the program a complete line of input first. Assume the user 123
, so the program reads 123\n
from the OS.
scanf
sees the newline that is not part of the number any more, and stops at that leaving the newline in the input buffer (within stdio). The second scanf
tries to read something that is not newlines, but can't do that, since the first thing it sees is a newline. If you check the return value of the scanf
calls, you'll see that the second scanf returns a zero, i.e. it couldn't complete the conversion you asked for.
Instead, read full lines at a time, with fgets
or getline
:
#include <stdio.h>
int main(void)
{
char *buf = NULL;
size_t n = 0;
double f;
getline(&buf, &n, stdin);
if (sscanf(buf, "%lf", &f) == 1) {
printf("you gave the number %lf\n", f);
}
getline(&buf, &n, stdin);
printf("you entered the string: %s\n", buf);
return 0;
}
For a longer discussion, see: http://c-faq.com/stdio/scanfprobs.html