tags:

views:

165

answers:

3

i have to make a user input num/percentage pairs. the code looks like:

while(choice != 0)
{
  printf("enter number");
  fgets(line, sizeof(line), stdin);//sizeof(line) is 6
  sscanf(line, "%d\n", choice);
  if(choice > 0)
  {
    printf("enter percentage\n");
    fgets(percent_line, sizeof(percent_line), stdin);//sizeof(percent_line) = 7
    sscanf(percent_line, "%f", &percentage);
    //add to an array holding numbers vs percentages
  }
}

the problem with this is that if i enter a string longer than 6 (or 5) at line 5, the remaining string goes into what is scanned at line 10, and if i enter a longer string that 7 (or 6) characters at line 10, the remaining input goes into the input at line 5. i want to destroy any leftover input. how do i do it?

+2  A: 

This isn't necessarily the best solution, but another approach might be to use fscanf():

while(choice != 0)
{
  printf("enter number");
  fscanf(stdin, "%d", &choice);
  if(choice > 0)
  {
    printf("enter percentage\n");
    fscanf(stdin, "%f", &percentage);
    //add to an array holding numbers vs percentages
  }
}

In this way you don't need the temporary line and percent_line buffers. The fscanf() function will automatically keep reading input until it gets what it is looking for - which means that if you just press Enter at the "enter number" prompt, the fscanf() function will not return and will keep reading input until you type a number. Also, error handling is not implemented in the above, I leave it as an exercise for the reader to fix the problem that happens when you enter something that isn't a number.

(Note that I also changed choice to &choice, which I think you intended in the first place.)

Greg Hewgill
A: 

You can check if there is \n in line - if not, use fgetc() in the loop until \n found, then proceed to following input.

qrdl
A: 

i think the latter one does the job pretty well. i dont mind if someone enters "acbgrt" instead of a number, i just want to make the program behave correctly. it will simply convert the string rubbish into 0, and then exit the loop.