Scan a string including spaces in C

2019-07-06 20:01发布

问题:

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?

回答1:

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.



回答2:

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);


回答3:

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);
}