Author Topic: scanf is shite  (Read 11054 times)

ahluka

  • Jackass IV
  • Posts: 794
  • Karma: +10/-201
scanf is shite
« 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?

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14305
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
scanf is shite
« Reply #1 on: August 26, 2005, 11:28:46 AM »
Try using gets().

ahluka

  • Jackass IV
  • Posts: 794
  • Karma: +10/-201
scanf is shite
« Reply #2 on: August 26, 2005, 12:26:17 PM »
Thanks, worked a dream :)

ygfperson

  • Founders
  • Posts: 601
  • Karma: +10/-1
    • Last.fm
scanf is shite
« Reply #3 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

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14305
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
scanf is shite
« Reply #4 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!)

sand_man

  • Super Jackass
  • Jackass II
  • Posts: 54
  • Karma: +10/-0
scanf is shite
« Reply #5 on: August 27, 2005, 06:06:26 AM »
Quote from: ober
Try using gets().

!! Ober you should know better! :p

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14305
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
scanf is shite
« Reply #6 on: August 27, 2005, 12:56:26 PM »
Bah... I haven't touched C in close to 3 years... what do you expect ;)

Tman

  • Lok'tar!
  • Jackass I
  • Posts: 12
  • Karma: +10/-0
scanf is shite
« Reply #7 on: September 04, 2005, 01:06:51 AM »
fgets() for input and then you can sscanf() for parsing I guess.