Search code examples
cgetchar

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


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?


Solution

  • 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;
    }