char *text;
text = malloc(256);
printf("Enter a sentence:");
scanf("%[^\n]s", text);
printf("%s",text);
Why doesn't the scanf
function work in this code?
I don't enter a sentence and immediately the program finished.
char *text;
text = malloc(256);
printf("Enter a sentence:");
scanf("%[^\n]s", text);
printf("%s",text);
Why doesn't the scanf
function work in this code?
I don't enter a sentence and immediately the program finished.
My guess is that your program runs, but the console closes before you can see the result.
Try to modify to the following:
char *text;
text = malloc(256);
printf("Enter a sentence:");
scanf("%[^\n]s", text);
printf("%s",text);
system("pause");
scanf("%[^\n]s", text);
is worse than gets()
. text[]
remains unassigned if only "\n"
entered *1, possible buffer overflow with no width limit. The s
in for format serves no purpose.
Instead use fgets()
with its input limit. Check return value.
#define N 256
char *text = malloc(N);
printf("Enter a sentence:");
if (fgets(test, N, stdin)) {
test[strcspn(test, "\n")] = '\0'; // Lop off potential trailing \n
printf("%s\n",text);
}
OP may also have trouble due to a prior scanf()
calls that leaves a dangling '\n'
in stdin
that chokes on this scanf("%[^\n]s"...
. Avoid using scanf()
at all until you know why it is weak.
Sigh - if you must stay with scanf()
, use below which 1) uses a leading space to consume all prior white-space like left-over '\n'
, 2) has a width limit and 3) tests the scanf()
success.
if (scanf(" %255[^\n]", text) == 1) { // No 's' in format.
printf("%s\n",text);
}
*1 This explains the "I don't enter a sentence and immediately the program finished." as prior input did not consume a '\n'
and OP's code does not either and so stops the scan. Since OP's code did not consume the '\n'
and scanf()
did not return 1 (which OP's code failed to test), following unposted code certainly fell into undefined behavior.