How to make a string to be "transformed into a number"

Asked

Viewed 75 times

2

I have an exercise to make the user type a word and it is transformed by its corresponding numbers from the ASCII table.

EXAMPLE: sara would print 115 97 114 97

that’s the code:

OBS: I put a fixed value on the vector just for testing. The result is generating two problems:

  • at the time of giving the values he PULA the first value (type prints ara and not sara)

  • And also print out some weird -14 numbers

    {
      int i;
      char texto[15] ;
    
      printf("digite uma palavra");
      gets(texto);
      fflush(stdin);
      scanf ("%c",texto);
    
      for (i=0; i<15; i++)
      {
        printf("Valor do elemento %d da string = %d\n",i, texto[i]);
      }
    
      getch();
    }
    
  • Depends on the programming language. It looks like you’re using C, does it check? If so, you can put C in tags?

  • yes. I’m sorry, I forgot to mention it’s in C

  • I solved it already, will I need to talk here what I did?

  • 2

    The ideal is to post as an answer, so others can know how you solved and, preferably, your line of thought on how you solved

  • 1

    The scanf has to be with %s and not %c and the use of gets. The fflush also not only is it unnecessary but it is not guaranteed to work on an incoming stream and typically only works on windows environment.

1 answer

1


Hi, trying to solve your problem I’ll list some string conversion functions that may be useful but remember to include the library: strings. h

double atof (const char *string);
//Converte uma string em um valor real.
int atoi (const char *string);
//Converte uma string em um valor imteiro.
int atol (const char *string);
//Converte uma string em um valor inteiro longo.
int sprintf (char *string, const *char format,
double number);
//Converte um número em string.
  • Thank you!! I managed to solve it

Browser other questions tagged

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