Convert a char array to an ints array

Asked

Viewed 137 times

1

Basically I’m trying to store a sequence of integers. I used a char array for when I input a sequence of 21 numbers it takes over as a string and after storing each number in each char array space. Then I wanted to copy this char array to an int array. The problem is that when I give as

input: 123443211234567890127

the program gives me how output: -3812344321123456789012

Can someone help me solve that -38?

void testa_nib () {

    int i,j=0,h=0,res=0;
    char str[21];
    int nib[21];

    for(i=0;i<=21;i++){
        scanf("%c",&str[i]);

    }
    for (h=0; h<21 ; h++) {
        char s;
        int tmp;
        s=str[h];
        tmp =  s - '0' ;
        printf("%d",tmp);
        nib[h]=tmp;
    }

int main() {

    testa_nib();
    return 0;
}
  • That’s a line break, um Chr( 10 ) - '0' gives -38 ( the \n is character 10 of the ASCII table, which is incorporated into Unicode as well, and in virtually all modern code pages)- missing sanitization in data entry.

  • but how does it happen if I have no char (10)?

  • In the scanf must have caught some. Try doing a hexadecimal print as debug, to be sure

  • can you explain to me how I do it? I’m still learning c

  • Test like this: scanf(" %c",&str[i]); - with a space before % - This causes the scanf remove blank characters, I’m trying to locate if there is already a post explaining this.

  • with the space before the % has already given, thank you very much, but can you tell me why this happened?

  • I posted a reply with more details

Show 2 more comments

1 answer

4


The value -38 already gives a good indication of the problem.

On this line here you make the characters of '0' to '9' are converted into a number from zero to nine:

tmp =  s - '0' ;

It’s just that there’s some non-numerical character in your string, by chance a line break, which is character 10 of the ASCII table (also incorporated in other more modern tables), this gives here -38:

tmp =  10 - '0';  // 0 tem o valor 48 na tabela ASCII

Whether to delete blank characters in a scanf, add a blank space before the %:

scanf(" %c",&str[i]);
//     ^- aqui

Further reading:

What happens in a conversion from a char to an int?

What is the difference between "NULL", "0" and 0?

How buffer works using printf and scanf?

  • 1

    Thank you very much, you helped so much!

Browser other questions tagged

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