How to convert a String Char by storing it in an Integer array in C?

Asked

Viewed 1,001 times

-4

How to convert a String Char and add to an Integer array?

  • Wants to convert a String in int and keep that int in a vector of ints that’s it ?

  • Be clearer on the question please.

1 answer

1

Basically what you should do is a technique known as casting, casting server for you to tell the computer that certain kind of data should be interpreted as the data you are casting, putting in other words you force a data of type A to be interpreted by the computer as a data of type B.

To do casting is very simple, just indicate the data you want it to be interpreted in front of the variable you want, it is very important that you put both the type and the variable between parentheses, to prevent the interpreter from misinterpreting, an example, let’s assume that you have a die of the type float in a variable called X and you want to assign this data to a variable B, only that as a whole, to do this just do the casting, then the answer would come out in such a way B = (int)(X);.

To facilitate your understanding I will recommend here a youtube video who teaches casting, and also a article of the IME (USP) on the subject.

Going straight to the answer of your question, but I recommend that before that you see the video and the article, and also that you practice / try to do it yourself, but without but delays here is the answer to your question.

#include <stdio.h>
#include <locale.h>

int main ()
{
    char strVar[] = "ABCabc";
    int vet[10];
    register int i;

    setlocale(LC_ALL, "");

    for ( i = 0; strVar[i] != '\0'; ++i )
        vet[i] = (int)(strVar[i]);

    printf("O que há escrito na string: %s.\n"
           "Seus respectivos em inteiro (tabela ASCII):\n", strVar);
    for ( i = 0; strVar[i] != '\0'; ++i )
        printf("%i = %c\n", vet[i], vet[i]);

    return 0;
}

A little tip, always when do a post here on stcak overflow is very specific with what you want, besides it is very interesting that you show what you have managed to do so far, so we can tell where exactly your mistake is, and also give a better answer to your question, also show the output it is giving, possible error messages or warnigs and etc.

I hope I’ve helped, good luck with learning gives language C bro :).

  • 1

    Although I recognize your effort and merit in answering the question the same is almost impossible to answer correctly, as it is not clear at all. Read my comment on the question and see how I interpret the question in a totally different way, as if it were a conversion of a char* for int manually or with atoi. In these cases I think it best not to answer until the author of the question is clear.

  • It makes sense, and you’re right, the meaning of his question was ambiguous even, should have expected some confirmation, but anyway thanks for the tip.

Browser other questions tagged

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