Read and print a 21-digit sequence

Asked

Viewed 58 times

-1

I want to enter a sequence of 21 numbers and save it in an array, and after that I want to print the sequence I saved in the array.

This is my code:

void testa_nib () {

    int i=0,c=0;
    int nib[21];
    for (i=0;i<22;i++) {
        c=getchar();
        c=c-'0';
        nib[i] = c;
    }

    for (i=0;i<=21;i++){
        printf ("%d",nib[i]);
    }

int main() {

    testa_nib();
    return 0;
}

This is my input:

123443211234567890127

This is my output:

-38123443211234567890127

  • Welcome to SOPT. :) Please translate your question, this is a community in Portuguese, or consider posting on the English site.

  • I thought you weren’t at SOPT, sorry

1 answer

1

One thing to note is that you are trying to assign the value of an integer a char, using the function getchar. Instead, use the scanf. Example

#include <stdio.h>

void testa_nib() {
    int i = 0, c = 0;
    int nib[21];

    for (i = 0; i < 22; i++) {
        scanf("%d", &nib[i]);
    }

    for (i = 0; i <= 21; i++) {
        printf("%d", nib[i]);
    }

}

int main() {
    testa_nib();
    return 0;
}

See working on onlinegdb: https://onlinegdb.com/HJJC02dH4

  • And I used the getchar to input that whole number with no spaces between each number. Using the scanf I could only make the function work if it was input: 1 2 3 4 3 2 1 1 2 3 4 5 6 7 8 9 0 1 2 7

  • That wouldn’t work. The function getchar reads only one typed character, all others would be ignored. https://www.dcc.fc.up.pt/~nam/lessons/0001/pi/slides/slipi0010/node9.html

  • but it worked, honestly tb got a CD in doubt because of that

Browser other questions tagged

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