Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getchar() into one dimensional array difficulties

Tags:

arrays

c

I am trying to develop a (simple) personal project which acts as a credit card validator using the classic 'MOD 10' rule.

I am having some difficulty with the first part of my project.

The aim is this:
Take 16 characters, one at a time, from the user.
Each time a character is entered, add it to the corresponding position in the array intInput.
Then later on (not shown), the function validator() is called, with the entire array as a parameter, and it is then validated as appropriate.

The difficulty is that it seems to be 'skip' over i each iteration, going up in iterations of 2, rather than 1. In addition, the values stored in the array appear to be differed to that expected.

char intInput[16];
char c;
int i;
for (i = 0; i <= 15; i++)
{
    printf("Please insert next char: \n");
    c = getchar();

    printf("\n Character entered:  \n");
    putchar(c);
    printf("\n");
    printf("Value of i is: %d \n", i); // debugging purposes

    intInput[i] = c; // add character input from user, into array for later processung
    printf("ADDED SOMETHING TO INTINPUT, VALUE: %c \n", intInput[i]); // debugging purposes
}

Am I using the functions getchar() and putchar() incorrectly?

like image 537
Masutatsu Avatar asked Feb 13 '26 07:02

Masutatsu


1 Answers

I am guessing getchar() read the \n character (which is the carriage return character) when the user press enter to validate the first character. You don't see it, but there is a character here, which make getchar() read again and i iterate again.

Try printing c with printf using an integer like this:

  printf("\n Character entered: %d\n", c);

It will print the ascii value of the character. Then you can refer to man ascii to check what character is really here, even if it is a character not displayed.

I tested with your code, and the problem appears to be really that. Now you have to found a way to bypass or ignore that, have fun :)

like image 158
Roger Avatar answered Feb 15 '26 21:02

Roger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!