Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems with scanf and gets

Status
Not open for further replies.

Greenleaf

Programmer
Feb 14, 2002
93
IT
Hello, here is a code that should read a certain number of strings. The problem is that the program doesn't stop to allow entering the first string. I can only write string n°2, n°3 and so on.
Is it perhaps the scanf before the for cycle that causes problems?

Code:
#define maxnumber 10

void main()
{
    char string[20];
    int index, numb;

    printf("\nHow many students? (less than %d) :", maxnumber);
    scanf("%d",&numb);
    for (index=0; index< numb; ++index)
    {  printf(&quot;\nWrite name of student nr %d :&quot;, index+1);
       gets(string);
    }
 }
 
I think the first gets reads the newline char after the number of students.
a dummy getchar() call after scanf(&quot;%d&quot;,&numb)
should help.
....
scanf(&quot;%d&quot;,&numb);
getchar();
....

I hope this helps!
 
Thank you Bugged! That helped!
I thought that scanf didn't read the newline char or the space char.
That's pretty tricky! :)
 
You can also use

scanf(&quot;%d&quot;,&numb);
fflush(stdin);

To flush the buffer instead of getchar(). You can also use

while ((getchar()) != '\n')
;

That will help if there is more than a single char in STDIN. It will read up to and inlcuding the '\n' and get rid of it.

-Tyler

 
Hello Gonzilla!
Thanks for your suggestion. fflush(stdin) worked quite well :) and now the compiler doesn't say anymore that &quot;the code has no effect in function main&quot; a propos of getchar(), although getchar worked as well.
I prefer the use of fflush rather then the while, I have a code more elaborated than the one I posted and fflush seems easier to control.
Is that true?
 
Yes. fflush() is much easier to use overall and can be used on more than just STDIN so it is more verstal. Some books say fflush() is usually used to flush the buffer when dealing with disk files (so that you can write what is in the buffer to the file), but it's ok to use in this case with STDIN. But, maybe you would only like to remove up to a certain character in the STDIN. If this is the case, you couldn't use fflush() because it flushes the entire buffer. Just something to think about.

Take a look at a good explanation of buffered and unbuffered IO. It will give you a good idea of how things work.

-Tyler
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top