除非我的电脑疯了或者我错过了什么。当我运行代码时,变量计数在每个内部 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++) {
i
是 strings
中的索引,从 0
到 a-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/