Read a string of characters with scanf ()

Posted on

Question :

My program should read large numbers ( 0 < = X

Answer :

Just be aware that when a n appears it stops reading:

while((scanf("%c", &caract) == 1) && ((caract >= '0') && (caract <= '9')) && caract != 'n')

Ah for cleaning the buffer before reading you can defer a “clean” way to start reading right:

#DEFINE clearbuffer  while(getchar()!='n');

and put clearbuffer before while :

clearbuffer;
while((scanf("%c", &caract) == 1) && ((caract >= '0') && (caract <= '9')) && caract != 'n')

clearbuffer is for cleaning your buffer so you are not reading garbage that might be in the buffer .

One more thing you can use getchar instead of scanf in the cycle:

while(caract=getchar() && ((caract >= '0') && (caract <= '9')) && caract != 'n')

    

Leave a Reply

Your email address will not be published. Required fields are marked *