How do I read in white spaces with scanf?

2019-09-16 19:49发布

It completely stops reading in code after it sees a space. How do I change my code so it reads in white space

char line[300];

printf("Enter a string to be checked: ");
scanf("%s", line);

the string I'm trying to input via redirection is:

( ( a a ) < > [ [ [ { [ x ] ]]] <>)

标签: c whitespace
4条回答
做个烂人
2楼-- · 2019-09-16 20:19

you should use fgets(line, size, stdin); as previously posted. you should never use gets(), as it expects a the same input size every time. Compilers, at least gcc, will warn you not to use it.

查看更多
▲ chillily
3楼-- · 2019-09-16 20:19

%s Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, and the array must be large enough to accept all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, whichever occurs first.

Need to choose a different format string. It's not really clear from your input string what exactly you're trying to accomplish.

查看更多
叼着烟拽天下
4楼-- · 2019-09-16 20:20

You can use fgets intsead of scanf. For example:

    fgets(line, 1024, stdin);
查看更多
冷血范
5楼-- · 2019-09-16 20:22

Please check the code..

  printf("Enter a string to be checked: ");
    gets( line);
    puts(line);

Output:-

Enter a string to be checked: ( ( a a ) < > [ [ [ { [ x ] ]]] <>)
( ( a a ) < > [ [ [ { [ x ] ]]] <>)
Press any key to continue . . .
查看更多
登录 后发表回答