如何解决如何修复不打印任何字符而只计算元音和字符并读取文件中的每个字符
我只想读取文件中的每个字符,其中我将字符从 A 到 Z 但程序每次都打印 A 并计算元音 4 和字符 25 但期望打印元音 5 和字符 26 如何修复此程序从过去 4 小时开始修复但没有任何进展? 代码:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
int i,count = 0,vowel_count = 0;
string file_name;
cout << "enter file name:";
cin >> file_name;
ifstream fin;
fin.open(file_name);
char ch;
while (!fin.eof()) {
fin.get(ch);
cout << ch;
while (fin >> ch) {
i = ch;
if ((i > 63 && i < 91) || (i > 96 && i < 123))
count++;
if (i == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowel_count++;
}
cout << "\n No. of Characters in a File : " << count;
cout << "\n No. of vowel characters in the File : " << vowel_count;
}
fin.close();
return 0;
}
解决方法
您在代码中有一些非常小的错误,我已为您修复。
另外,我添加了一个检查,文件是否可以打开。大多数情况下都是这个问题。
请看下面:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
int count = 0,vowel_count = 0;
string file_name;
cout << "\nEnter file name: ";
cin >> file_name;
ifstream fin(file_name);
if (fin) {
char ch;
while (fin.get(ch)) {
cout << ch;
if ((ch >= 'A' && ch <= 'Z') || (ch > 'a' && ch <= 'z'))
count++;
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowel_count++;
}
fin.close();
cout << "\n No. of Characters in a File : " << count;
cout << "\n No. of vowel characters in the File : " << vowel_count;
}
else std::cerr << "\n\n*** Error. Could notopen '" << file_name << "'\n\n";
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。