C++多字符串字符统计时后续字符串首字符未计数问题排查
C++多字符串统计时后续字符串首字符未计数的问题分析
我编写了一段C++代码,用于统计多个字符串中的元音、辅音及空格数量,但仅第一个字符串的统计结果正确,后续第2、3个及更多字符串的首字符未被计数,请问这是什么原因?
代码如下:
#include <iostream> using namespace std; int main() { string sentence; int countv = 0, countc = 0, countspace = 0, number, s = 1; cout << "How many sentence would you like to check? - "; cin >> number; while(s <= number) { cout << "\nSentence " << s << ":"; cin.ignore(); getline(cin, sentence); for(int i = 0; i < sentence.length(); i++) { if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u') countv++; else if(isspace(sentence[i])) countspace++; else countc++; } cout << "\nSentence " << s << " result:"; cout << "\nThere are " << countv << " vowels in the sentence."; cout << "\nThere are " << countc << " consonants in the sentence."; cout << "\nThere are " << countspace << " whitespace in the sentence."; countc = 0, countv = 0, countspace = 0; s++; cout << "\n"; } }
问题原因
问题出在cin.ignore()的重复调用上:
- 当用
cin >> number读取数字后,输入缓冲区会残留一个换行符(按下回车确认数字时产生)。第一次循环时,cin.ignore()会跳过这个换行符,让getline能正确读取第一个字符串。 - 从第二次循环开始,输入缓冲区里没有残留的换行符了,此时
cin.ignore()会直接跳过你输入的当前字符串的首字符,导致后续字符串的首字符未被统计。
解决方案
只需要在读取数字后调用一次cin.ignore(),清除缓冲区里的换行符,不要在每次循环中重复调用:
修改后的代码:
#include <iostream> #include <limits> // 包含头文件以使用numeric_limits using namespace std; int main() { string sentence; int countv = 0, countc = 0, countspace = 0, number, s = 1; cout << "How many sentence would you like to check? - "; cin >> number; // 一次性清除缓冲区中直到换行符的所有残留字符 cin.ignore(numeric_limits<streamsize>::max(), '\n'); while(s <= number) { cout << "\nSentence " << s << ":"; getline(cin, sentence); // 不再重复调用ignore for(int i = 0; i < sentence.length(); i++) { if(sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u') countv++; else if(isspace(sentence[i])) countspace++; else countc++; } cout << "\nSentence " << s << " result:"; cout << "\nThere are " << countv << " vowels in the sentence."; cout << "\nThere are " << countc << " consonants in the sentence."; cout << "\nThere are " << countspace << " whitespace in the sentence."; countc = 0, countv = 0, countspace = 0; s++; cout << "\n"; } }
额外说明
- 使用
cin.ignore(numeric_limits<streamsize>::max(), '\n')比单纯的cin.ignore()更可靠,它会清除换行符之前的所有残留字符,避免因输入数字后多输入其他字符导致的问题。 - 如果只需要统计空格(而非所有空白字符如制表符),可以把
isspace(sentence[i])改为sentence[i] == ' '。
内容的提问来源于stack exchange,提问作者Khairul Amri
相关产品推荐
相关产品推荐

