Use of getchar() in for statement does not work as expected

109 views Asked by At

The code below does not work as expected, somebody can give me some suggestions?

#include <stdio.h>
int main(){
    int i, k=0, j=0;
    char hex[50], c;
    for (i=0; (c=getchar()) != EOF && (c=getchar()) != '\n'; i++) {
        hex[i] = c;
        j++;
    }
    if (c == 'n') {
        hex[i] = 'n';
        i++;
    }
    hex[i] = '\0';
    for (k=0; k<i; k++) {
        printf("%c", hex[k]);
    }
    printf("\n%d %d %d\n", i, j, k);
    return 0;
}

if I input:

abc

I suppose the output should be:

abc
4 3 4

However, in my Xcode IDE the output is:

b
1 1 1

Somebody can help me to debug my code?

2

There are 2 answers

2
BLUEPIXY On BEST ANSWER

fix like this

#include <stdio.h>

int main(void){
    int i, j, k, c;//The type of c must be int.
    char hex[50];

    for (j = i = 0; i < sizeof(hex)-1 && (c=getchar()) != EOF && c != '\n'; i++, j++) {//The input part should be one.
        hex[i] = c;
    }
    if (c == '\n') {//n is typo as \n
        hex[i] = '\n';
        i++;
    }
    hex[i] = '\0';

    for (k = 0; k < i; k++) {
        printf("%c", hex[k]);
    }
    printf("%d %d %d\n", i, j, k);//newline already include.
    return 0;
}
1
cokceken On

When you say

for (i=0; (c=getchar()) != EOF && (c=getchar()) != '\n'; i++)

compiler evaluates c=getchar()) != EOF first and takes the first char as input. Then if it is true it evaluates (c=getchar()) != '\n'. Now value of c is 'b'.

You should say

for (i=0; (c=getchar()) != EOF && c != '\n'; i++)

because c is already initialized as 'a'

EDIT: as @Stargateur says you should use while when you don't know how long the operation goes and when you are waiting for some input to end it. Use for loop for restricted operations like operating on known number of items (for example array of a struct).