繁体   English   中英

在for语句中使用getchar()不能按预期工作

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

下面的代码无法正常工作,有人可以给我一些建议吗?

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

如果我输入:

abc

我想输出应该是:

abc
4 3 4

但是,在我的Xcode IDE中,输出为:

b
1 1 1

有人可以帮助我调试代码吗?

当你说

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

编译器首先评估c=getchar()) != EOF并将第一个字符作为输入。 然后,如果为true,则计算(c=getchar()) != '\\n' 现在c值为'b'

你应该说

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

因为c已经被初始化为'a'

编辑:正如@Stargateur所说while当您不知道该操作进行了多长时间以及正在等待结束该操作的输入时,应使用。 使用for循环为受限制的操作等上已知数量的项目(一个结构的示例性阵列)的操作。

像这样修复

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM