简体   繁体   中英

Scan a string including spaces in C

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM