Originally Posted by
sangamesh
But if I change the scanf statement from
Code:
scanf("%[^\n]",usr_in);
to
Code:
scanf("%s", usr_in);
It runs well. But it stores only the first word. Any hints why this scanf giving segfault
Just a tip, scanf separates strings when it encounters a space or newline (and maybe something else, correct me if I'm wrong)
typing in:
Code:
char Variable1[80], Variable2[80], Variable3[80];
scanf("%s", Variable1);
scanf("%s%s", Variable2, Variable3);
printf("%s\n%s%s", Variable1, Variable2, Variable3);
(if we type in "Hello World" into the console) it would return
Scanf sees a space and ends off the variable there, thats why it would require 2 variables to actually take in "Hello World!"
To get around this (and a safe way to do so) is to use fgets. An example of this would be something such as:
Code:
char Variable[80];
fgets(Variable, sizeof Variable, stdin);
Its not only faster than scanf (atleast thats what I heard because scanf has to check if its taking in an int,double,float,string, and formatting) its also safer because you're limiting how much data can be taken in (that "sizeof Variable") which will make sure the buffer doesn't overflow. Correct me if I'm wrong with any of this, its all of the top of my head.