Scan a string containing spaces in C

In my code:

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

Input:

hi how are you

Conclusion:

hi

but not

hi how are you

what can i do to fix this?

+3
source share
3 answers

Take a look at fgets

The fgets () function reads no more than one less than the number of characters given n from a given stream and saves them in line s. Reading stops when a new line begins at the end of a file or an error occurs. A new line, if any, is retained. If any characters are read and there is no error, the `\ 0 'character is added to end the string.

+3
source

I assume you are looking

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

. , -

ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream);
+1

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);
}
+1
source

Source: https://habr.com/ru/post/1776746/


All Articles