I have done it 4-5 years ago, that to read a whole line of text (including space) using scanf function.
When I was preparing for my exams, I went back to the old days of a “C” student. Nowadays I’m a bit used with C++. So I forgot the format specifier to specfy inside the scanf function. Finally my memory retrieved it back
Here’s it is:
char name[100];
printf(“Enter the name:”);
scanf(“%[^\n]“,name);
Something cool no?
19 Comments
You have to make sure that:
name[99] = ”;
It’s vulnerable to buffer overflows
Use fflush(stdin); to avoid looping!?
THANK YOU. Ive been searching forever online for this!!!!!!!!!!!! you rock
>It’s vulnerable to buffer overflows
To avoid that declare a maximum field
if ( scanf(“%99[^\n]“, name) == 1) { /* do something */} will do it. However does leave still input in the stdin buffer if more than 99 keys where typed.
>Use fflush(stdin); to avoid looping!?
That’s invoking undefined behavior.
fflush() is only for OUTPUT streams, and not for INPUT like stdin.
Hey thanks a lot for that piece of code! Works great!
The strange thing is that the string variable doesn’t need a preceeding ampersand (&).
Quite surprising….I’d like to know how that happens…
fflush(stdin) works fine for the input, i have use it in many proyects i haver worked and havent given me any problems.
thnx dear….
you are awsom
I wish I’d found this blog posting two hours ago.
Awesome. This works great
Use fgets instead…
The version that is not vulnerable to buffer overflows is:
char name[100];
printf(”Enter the name:”);
fgets(name,100,stdin);
Hope that helps…
Cool reminder. I used this thing to skip comments in a file :
// eat spaces
// match ‘#’
// capture and discard everything until end of line
fscanf(stream, ” #%*[^\n]“);
Cheers
i didn’t get tis…. none of the codes worked for me,including the one containing regular expressions.
how do we read a line from the user in C.
Hey this is not working…..
(To Sub)Two questions back:
Here is a simple snippet to answer your question:
#include
int main(int argc, char *argv[])
{
char first_name[100];
printf(“What is your name? “);
gets(first_name);
printf(“\nNice to meet you %s!”,first_name);
return 0;
}
Try this, I hope it helps in some small way…..
Oddly,
The post deleted what was in the brackets after include (which was simply “stdio.h”)
Or, we can just use
#include
int main()
{
char name[99];
printf(“What is your name? “);
scanf(“%s”,&name);
printf(“Hello, %s. How are you?\n”,name);
return(0);
}
Same result.
I would like to see more blog entries like this one
2 Trackbacks
[...] (what’s surprising is that abc doesn’t need an ampersand preceeding it) Got it from here and there are comments about scanf being vulnerable to buffer overflows. Is that true? So [...]
[...] Datei lesen und an bestimmer Stelle verändern Am besten ist vielleicht, immer ein komplette Zeile einzulesen. Dann musst du immer prüfen, ob du nun an dem zu editierenden Block angekommen bist. Das kann man [...]