EntropySink

Technical & Scientific => Programming => Topic started by: ahluka on August 26, 2005, 10:22:35 AM

Title: scanf is shite
Post by: ahluka on August 26, 2005, 10:22:35 AM
I've got a loop that outputs a prompt and reads in a 'command' into a buffer:

Code: [Select]

while (strcmp (cmd_in, "exit") != 0) {
    printf (">> ");
    scanf ("%s", cmd_in);
}


However, if I type something like 'hello world', the prompt is output twice. I placed a printf in there to output cmd_in 'in-between' the loops to see it's value, like so:

Code: [Select]

while (strcmp (cmd_in, "exit") != 0) {
    printf (">> ");
    scanf ("%s", cmd_in);
    printf ("%s\n", cmd_in);
}


Now if I type a space (ala 'hello world') then I see this:

Code: [Select]

>> hello world
hello
>>
world
>>


So it seems scanf takes spaces as deliminaters for new input? It's really annoying now because I can't find any way to surpress it.

Any ideas?
Title: scanf is shite
Post by: ober on August 26, 2005, 11:28:46 AM
Try using gets().
Title: scanf is shite
Post by: ahluka on August 26, 2005, 12:26:17 PM
Thanks, worked a dream :)
Title: scanf is shite
Post by: ygfperson on August 26, 2005, 01:57:31 PM
gets and fscanf are unsafe because they don't check for the size of the input. Use fgets, which includes a parameter to limit the number of letters read
Title: scanf is shite
Post by: ober on August 26, 2005, 02:11:22 PM
That's what you get taking advice for a guy that doesn't use C/C++ for a living (or in the past 2 years!)
Title: scanf is shite
Post by: sand_man on August 27, 2005, 06:06:26 AM
Quote from: ober
Try using gets().

!! Ober you should know better! :p
Title: scanf is shite
Post by: ober on August 27, 2005, 12:56:26 PM
Bah... I haven't touched C in close to 3 years... what do you expect ;)
Title: scanf is shite
Post by: Tman on September 04, 2005, 01:06:51 AM
fgets() for input and then you can sscanf() for parsing I guess.