Scan a string including spaces in C

2019-07-06 20:06发布

In my code:

scanf("%s", &text);
printf("%s\n", text);

Input:

hi how are you

Output:

hi

and not

hi how are you

what can I do to fix it?

3条回答
ら.Afraid
2楼-- · 2019-07-06 20:34

Use fgets to get your input:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    char text[80];
    fgets(text, sizeof(text), stdin);
    printf("%s\n", text);
}
查看更多
不美不萌又怎样
3楼-- · 2019-07-06 20:36

Look at fgets

The fgets() function reads at most one less than the number of characters specified by n from the given stream and stores them in the string s.Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a `\0' character is appended to end the string.

查看更多
成全新的幸福
4楼-- · 2019-07-06 20:47

I suppose you're looking for

ssize_t getline(char **lineptr, size_t *n, FILE *stream);

Which will read up to a newline delimiter. Or if you're using some other delimiter

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
查看更多
登录 后发表回答