繁体   English   中英

我不确定为什么我的嵌套 while 循环在第一次迭代后停止

[英]I'm not sure why my nested while loop is stopping after the first iteration

我必须编写一个 C 程序,要求用户输入一个字符串,并返回字符串中每个字母出现的次数(即 a 出现 3 次)。 例如,如果用户输入以下字符串:

Hello

它应该返回以下内容

a or A appears 0 times 
b or B appears 0 times 
c or C appears 0 times 
d or D appears 0 times
e or E appears 1 times
(it does this for the whole alphabet) 

代码:

#include<stdio.h>
#include<stdlib.h>
#define MAX 1000

int main(){

    char str[MAX];
    int count[26]={0};

    printf("Enter your string \n");
    fgets(str,sizeof(str),stdin);

    char str1[]="abcdefghijklmnopqrstuvwxyz";
    char str2[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int i=0;
    int j=0;
    while(i<26){

        while(str[j]!='\0'){
            if(str[j]==str1[i]||str[j]==str2[i]){
                count[i]++;
            }
            j++;
        }

        printf("Letter %c or %c appears %d times\n",str1[i],str2[i],count[i]);
        i++;

    }
    return 0;
}

用我现在所拥有的它扫描 a 然后在此之后停止并且每隔一个字母就返回零

在内部 while 循环之后

    while(str[j]!='\0'){
        if(str[j]==str1[i]||str[j]==str2[i]){
            count[i]++;
        }
        j++;
    }

j变得等于strlen( str )并且str[j]等于'\\0'所以在外循环的下一次迭代中,内循环的条件等于逻辑假。 您至少需要在内循环之前将变量j重置为零。

    j = 0;
    while(str[j]!='\0'){
        if(str[j]==str1[i]||str[j]==str2[i]){
            count[i]++;
        }
        j++;
    }

这个逻辑错误的原因是变量j没有在使用它的作用域中声明。 尝试在使用它们的最小范围内声明变量。

而不是内部 while 循环,最好编写一个 for 循环,如

for ( size_t j = 0; str[j] != '\0'; j++ )
{
    //...
}

暂无
暂无

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

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