0

look at the code given below

#include <stdio.h>

int main()
{
    char str[20];
    printf("Enter a string : ");
    scanf("%s", str);
    printf("String : %s", str);
    return 0;
}

output will be,

Enter a string : Hello world

String : Hello

my question is why it take only first word as input?

1
  • 2
    scanf() reads to first whitespace Commented Sep 21, 2021 at 9:17

2 Answers 2

0

my question is why it take only first word as input?

Because that's exactly what the documentation says that the %s specifier should do:

Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.

https://www.cplusplus.com/reference/cstdio/scanf/

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the following methods

Method 1:

scanf("%[^\n]",str);

Method 2:

fgets(str, MAX_LIMIT, stdin);

4 Comments

Please edit the answer to exclude gets(). That function is obsolete and dangerous. Even the manual page says "Never use this function." See [stackoverflow.com/questions/1694036/…
Method 2 is wrong
@klutt ohh sorry, it was a typo.
And I have to say that method 1 seems a bit odd. Looks like you're about to read one character extra after the newline. What's it supposed to do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.