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?

klutt
  • 30,332
  • 17
  • 55
  • 95

2 Answers2

0

You can use the following methods

Method 1:

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

Method 2:

fgets(str, MAX_LIMIT, stdin);
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31
  • 1
    Please edit the answer to exclude `gets()`. That function is obsolete and dangerous. Even the manual page says "Never use this function." See [https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used](reasoning) – George Sep 21 '21 at 09:36
  • Method 2 is wrong – klutt Sep 21 '21 at 09:57
  • @klutt ohh sorry, it was a typo. – Saurabh Dhage Sep 21 '21 at 10:09
  • 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? – klutt Sep 21 '21 at 10:10
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/

klutt
  • 30,332
  • 17
  • 55
  • 95