c - 2个while循环内的变量不会重置

标签 c

除非我的电脑疯了或者我错过了什么。当我运行代码时,变量计数在每个内部 while 循环之后不会重置为零。 前任。如果我输入:
xxx
yyyy
输出计数为1-9。但应该是1-4和1-5。

int main(){

    char string[500][500];
    int letterWords[15]={0};

    printf("Enter several lines of text.\n");
    scanf("%[^\t]", string);

    int a=0, b=0;

    int count=0, i;

    while(string[a][0]!='\0'){
        while(string[a][b]!='\0'){
            count++;
            b++;
            printf("%d\n", count);
        }
        printf("\n");
        count-=2;
        letterWords[count]++;
        a++;
        b=0;
        count=0;  //the count doesn't reset to 0 for some reason
    }

    for(i=0;i<15;i++){
        if(letterWords[i]==0){
            continue;
        }
        printf("%d %d\n", i+1, letterWords[i]);
    }

}

最佳答案

我冒昧地 reshape 了代码(否则有太多东西需要改变)

int main() {

    char string[500][500];
    int letterWords[15]={0}; // max line length is 14
    int a,i,count;

    printf("Enter several lines of text (end with ^D).\n");
    for(a=0 ; a < 500 && fgets(string[a], 500, stdin) ;  a++) /* nothing */;

    for(i=0 ; i<a ; i++) {
        for(count=0 ; string[i][count] && string[i][count] != '\n' ; count++)  /* nothing */ ;
        printf("Line %d: %d\n", i, count);
        letterWords[count]++;
    }

    for(i=0 ; i<15 ; i++) {
        if(letterWords[i]) {
            printf("%d %d\n", i, letterWords[i]);
        }
    }

    return 0;
}

说明:

for(a=0 ; a < 500 && fgets(string[a], 500, stdin) ;  a++) /* nothing */;

使用fgets读取给定最大长度的行。行计数器是a
要完成输入,用户在空行上按 Control-D (EOF)。
当满足 EOF(或发生错误)时,fgets 返回 NULL

for(i=0 ; i<a ; i++) {

istrings 中的索引,从 0a-1

    for(count=0 ; string[i][count] && string[i][count] != '\n' ; count++)  /* nothing */ ;

不需要其他变量。 count 计算行中的字符数,并在满足 \n\0 时停止。

    printf("Line %d: %d\n", i, count);
    letterWords[count]++; // Increment the line-counter
}

请注意,每行的字符数不得超过 14 个。最后,

for(i=0 ; i<15 ; i++) {
    if(letterWords[i]) {
        printf("%d %d\n", i, letterWords[i]);
    }
}

打印结果,Length Number_of_lines_of_that_length

关于c - 2个while循环内的变量不会重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47427179/

相关文章:

c - 在没有双重评估的情况下在 Clang 中实现 min() 和 max()

c - 使用 pthread 的简单用餐哲学家

c++ - `if(CONSTANT) { ... }` 是否在 C/C++ 中进行了优化?

c - 如何在不使用 system、popen、fork、exec 的情况下在 C/Linux 中执行外部命令?

c - 求三角形中顶点a、b、c的等距点。语言是c

c - 在 Ubuntu 的终端中查找文件及其在目录中的路径,argv [2] 中给出的文件名

c++ - CMake 包含和源路径与 Windows 目录路径不同

c++ - 随机生成可被N整除的数字的最佳算法

c - C中指向特定地址的指针

c - C winapi中服务器的实现