C语言for循环未遍历字符串全部字符?新手技术求助
问题排查与修复方案
问题根源
所有计数函数(count_letters、count_words、count_sentences)中的循环条件完全错误:
原代码使用for (int i = 0; i < text[i]; i++),这是拿循环索引i和当前字符的ASCII值做比较,而非遍历到字符串结尾。
C语言中字符串以'\0'(ASCII值为0)作为结束标志,当循环索引i增长到某个值时,若当前字符的ASCII值小于i,循环会提前终止,导致后续字符未被统计。比如第二个测试文本中,当i增加到某个位置时,text[i]的ASCII值小于i,循环直接停止,因此句子末尾的.没被检测到,单词和字母统计也不完整。
修复方案
将三个函数的循环条件修改为检查当前字符是否为字符串结束符'\0',同时优化冗余代码提升鲁棒性:
修复后的完整代码
#include <cs50.h> #include <stdio.h> #include <ctype.h> // 用于简化字母、空格判断 int count_letters(string text); int count_words(string text); int count_sentences(string text); int main(void) { string text = get_string("Type in the text: "); int n1 = count_letters(text); int n2 = count_words(text); int n3 = count_sentences(text); printf("Letters: %i\n", n1); printf("Words: %i\n", n2); printf("Sentences: %i\n", n3); } int count_letters(string text) { int letters = 0; for (int i = 0; text[i] != '\0'; i++) { // 用isalpha直接判断是否为字母,包含大小写 if (isalpha(text[i])) { letters++; } } return letters; } int count_words(string text) { int words = 0; int i = 0; // 跳过开头的连续空格 while (text[i] != '\0' && isspace(text[i])) { i++; } // 遍历字符串,遇到空格且下一个字符非空格时计数 for (; text[i] != '\0'; i++) { if (isspace(text[i]) && text[i+1] != '\0' && !isspace(text[i+1])) { words++; } } // 非空字符串的单词数=有效空格数+1 if (text[0] != '\0') { words++; } return words; } int count_sentences(string text) { int sentences = 0; for (int i = 0; text[i] != '\0'; i++) { if (text[i] == '!' || text[i] == '?' || text[i] == '.') { sentences++; } } return sentences; }
关键修改点说明
- 循环条件修正:所有
for循环的终止条件改为text[i] != '\0',确保遍历完整个字符串,不会提前终止。 - 字母判断优化:引入
<ctype.h>头文件,用isalpha()替代手动ASCII范围判断,代码更简洁可靠。 - 单词计数鲁棒性提升:原代码默认初始单词数为1,若输入文本开头/结尾有空格会统计错误。修复后的代码先跳过开头空格,再通过检测有效空格(空格后接非空格字符)计数,最后根据字符串是否为空调整结果,适配更多输入场景。
测试第二个示例文本“aaa aaa aaa aaa aaa aaa aaa aaa aaa bbb.”时,会正确返回:字母数30、单词数10、句子数1。
内容的提问来源于stack exchange,提问作者VidR
相关产品推荐
相关产品推荐

