Jump to content

About scanf in loop

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
Max.89

Max.89

    Newbie

  • Members
  • Pip
  • 9 posts
I have a problem with the function scanf from the stdio.h library.
For example if I write something like this:
char choice;

while(choice != ' ')
{
  printf("Insert a char (space to finish):");
  scanf("%c",&choice);
  ...
}
The sentence in printf() is printed in output twice.
It only happens with %c and not with %d inside loops(both while and for).
Why?
Thanks in advance.

Edited by WingedPanther, 01 January 2009 - 06:19 AM.
add code tags (the # button)


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Without seeing the rest of your code, it's hard to say. You shouldn't be using %d, which suggests there is a problem elsewhere in the code.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
Max.89

Max.89

    Newbie

  • Members
  • Pip
  • 9 posts
I don't know if the rest of the code matters because it's not the first time I have this problem.
Every single program in which I used %c with printf or scanf inside a loop printed the text twice.I always avoided the problem using %d instead of %c but now I need to use characters.
This is a function of my code:

void printList(listElementType *listPtr)

{

  

  while(listPtr != NULL)

  {

    printf("--->%c",listPtr->elem);

    listPtr = listPtr->nextPtr;

  }

}

This is the output for a single printf
--->char--->char

Maybe in every program I made I did the same mistake in some part of the source code,but if it was a logical error it should have showed the double text output also for %d and not only for %c.

#4
Phoenixz

Phoenixz

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 256 posts
I dunno if this is right or not, but just an attempt of helping you.. :P If you used a previous scanf did you use fflush(stdin); also to clear it?

#5
Max.89

Max.89

    Newbie

  • Members
  • Pip
  • 9 posts
You are right I didn't use fflush function...
Now it works.
Thanks.

#6
dargueta

dargueta

    Writes binary right handed and hex left handed

  • Moderators
  • 4,713 posts
It shouldn't. fflush() is only defined for output streams. Even if it does work for you on your computer, there is no guarantee it'll work anywhere else.