Read a string with scanf()

Asked

Viewed 631 times

3

My program must read big numbers(0<=X<=10 (100)), what I’m doing is he reads/interprets the typed numbers as char and store in a chained list.

My show was fine, until I put one scanf("%d")(whose function is to read a natural number of cases) above the scanf who reads the numbers X...

So, I would like to know how to format the input of scanf() so that it can read numeric characters one by one and at the end when pressing ENTER.

There is a solution?

Part of my code:

scanf("%d", &t);

while(caso <= t)
{
   lista_ini = NULL;

   while((scanf("%c", &caract) == 1) && ((caract >= '0') && (caract <= '9')))
   {
      lista_ini = lst_insere(lista_ini, (caract - 48));
   }
...

Thanks.

1 answer

4


Just ensure that when one appears \n he stops reading:

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

Ah for the cleaning of the buffer before reading can defer a way to "clean" to start reading properly:

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

and put the clearbuffer before the while:

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

The clearbuffer is to clean up your buffer so you’re not reading trash that might be on buffer reading.

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

while(caract=getchar() && ((caract >= '0') && (caract <= '9')) && caract != '\n')
  • I got it all figured out, buddy! Thanks

  • I just couldn’t accomplish using the getchar, but okay.

  • I’ll set an example for you tomorrow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.