c++ - 程序计数辅音错误
问题描述
我正在尝试制作一个计算文本文件中所有元音和所有辅音的程序。但是,如果文件中有诸如 cat 之类的单词,则它说有 3 个辅音和 1 个元音,而应该有 2 个辅音和 1 个元音。
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
int main(void)
{
int i, j;
string inputFileName;
ifstream fileIn;
char ch;
cout<<"Enter the name of the file of characters: ";
cin>>inputFileName;
fileIn.open(inputFileName.data());
assert(fileIn.is_open());
i=0;
j=0;
while(!(fileIn.eof())){
ch=fileIn.get();
if (ch == 'a'||ch == 'e'||ch == 'i'||ch == 'o'||ch == 'u'||ch == 'y'){
i++;
}
else{
j++;
}
}
cout<<"The number of Consonants is: " << j << endl;
cout<<"The number of Vowels is: " << i << endl;
return 0;
}
解决方案
在这里您检查eof
状态是否已设置,然后尝试读取char
. eof
在您尝试读取超出文件末尾之前不会设置,因此读取char
失败,但您仍然会计算char
:
while(!(fileIn.eof())){
ch=fileIn.get(); // this fails and sets eof when you're at eof
因此,如果您的文件仅包含 3 chars
, c
,a
并且t
您已阅读 ,t
您会发现eof()
未设置。它将在您尝试阅读下一个时设置char
。
更好的方法是检查fileIn
提取后是否仍处于良好状态:
while(fileIn >> ch) {
有了这个,计数应该加起来。但是,所有特殊字符都将被视为辅音。为了改进这一点,您可以检查是否char
是一个字母:
#include <cctype>
// ...
while(fileIn >> ch) {
if(std::isalpha(ch)) { // only count letters
ch = std::tolower(ch); // makes it possible to count uppercase letters too
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
i++;
} else {
j++;
}
}
}
推荐阅读
- rust - 为什么类型推断在添加期间不起作用,而在分配期间起作用
- python - 如何让 python 脚本在 sys.excepthook 之后继续工作?
- javascript - WHM API:每次以随机顺序获取输出 JSON 元素
- python - 使用 tflearn 构建 CNN
- arduino - Adafruit MAX31856 热电偶传感器出现问题
- visual-studio-code - 运行 Visual Studio Code 任务时打印调试消息
- visual-studio-code - 如何在 VS Code 扩展中访问文件内容
- verilog - 由于参数,FF/Latch 的常数值为 0
- html - 使用knitr导入html输出的字体类型
- php - ZMQ 上下文不是从浏览器/PHP 发送数据,而是从 CMD/CLI (Windows 10) 工作