Gal
Gal

Reputation: 23662

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?

Upvotes: 3

Views: 11895

Answers (3)

GreenMatt
GreenMatt

Reputation: 18590

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

Upvotes: 1

falstro
falstro

Reputation: 35687

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

Upvotes: 1

The Archetypal Paul
The Archetypal Paul

Reputation: 41769

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.

Upvotes: 3

Related Questions