Why OP code fails: With user input like 5 Enter a space b Enter.
The first scanf()
consumes "5"
, leaving "\na b\n"
for the next scanf()
. That scanf()
scans nothing and saves nothing into str
as the first char
is a '\n'
.
scanf("%d",&n);
scanf("%[^\n]s",str);
For reading a line scanf("%[^\n]s",str);
has a number of problems.
There is not reason for the s
in "%[^\n]s"
"%[^\n]"
will not save anything into str
if input is "\n"
.
No protection against reading too much data.
Code should check the return value from scanf()
.
As suggested by many, use fgets()
char str[500];
if (fgets(str, sizeof str, stdin) == NULL) HandleEOForIOerror();
// to remove '\n'
size_t len = strlen(str);
if (len > 0 && str[len-1] == '\n') str[--len] = 0;
printf("%s",str);
To read the number, recommend the same, use fgets()
#include<stdio.h>
int main(void) {
int n;
char str[500];
if (fgets( str, sizeof str, stdin) return -1;
if (1 == sscanf(str, "%d",&n)) {
printf("%d\n",n);
}
if (fgets( str, sizeof str, stdin) return -1;
printf("%s",str);
return 0;
}