-2

I need to get words from user which contains space as I expressed at title with struct statement.

For example :

#include <stdio.h>

struct knowledge
{
   char name[30];
}person;


int main()
{
   scanf("%s",person.name);
   printf("\n\n%s",person.name);
}

When I run this program and enter a sentence like "sentence" there is no problem. It show me again "sentence". However, when I enter "sentence aaa" it shows me just first word ("sentence"). What is the matter here? Why it doesn't show me all ("sentence aaa") I entered?

NoWeDoR
  • 7
  • 3

2 Answers2

0

%s format specifier stops scanning on encountering either whitespace or end of stream. hence, you cannot input a "sentence" with space using scanf() and %s.

To scan a "whole line" with space, you need to use fgets(), instead.

Natasha Dutta
  • 3,242
  • 21
  • 23
0

Instead of scanf() use

fgets(person.name,sizeof(person.name),stdin);

It is always a bad idea to use scanf() to read strings. The best option is to use fgets() using which you avoid buffer overflows.

PS: fgets() comes with a newline character

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • You're very right, but instead of _only_ instructing someone to use some alternative, you may want to explain the reason also. Just thought of mentioning. :-) – Natasha Dutta Jun 09 '15 at 16:16
  • @NatashaDutta I have explained why and how to use fgets – Gopi Jun 09 '15 at 16:22
  • That is not required, you see. Point them to the man page, let them read and come back if they have any doubt. What I was asking is to tell them why **not to** use something. That makes more sense, IMO. Anyways, it's just a suggestion, my own point of view. Peace. :-) – Natasha Dutta Jun 09 '15 at 16:25