我的字符计数代码计算错误.为什么

My character counting code is miscounting characters. Why?

本文关键字:计算 错误 为什么 代码 字符 我的      更新时间:2023-10-16

输入文件有4项,但程序似乎在计算更多项。我试图创建一个函数来计算文本文件中大写的项目。

#include<iostream>
#include<fstream>
using namespace std;
bool ckeckCap(char ch){
if((ch>='A')&&(ch<='Z')){
return true;
return false;
}
}
int main(){
ifstream inputFile;
char ch;
bool cap;
int capa=0;
int count=0;
inputFile.open("input.txt");
if(!inputFile.is_open()){
cout<<"Error opening...Aborting"<<endl;
return 0;
}
while(!inputFile.eof()){
inputFile>>ch;
cap=ckeckCap(ch);
if(cap==true)
capa=capa+1;
//inputFile>>ch;
}
cout<<capa;
return 0;
}

由于,您看到从文件中读取的条目数量不一致

while(!inputFile.eof())

这是错误的。请参阅为什么循环条件(即`while(!stream.eof(((`(中的iostream::eof被认为是错误的?

此外,这个:

bool ckeckCap(char ch){
if((ch>='A')&&(ch<='Z')){
return true;
return false;
}
}

应该是

bool ckeckCap(char ch){
if((ch>='A')&&(ch<='Z')){
return true;
}
return false;
}

或者更确切地说

bool ckeckCap(char ch){
return ((ch>='A')&&(ch<='Z'));
}

请注意,这是如何更短,更容易阅读,你不能犯同样的错误,如上所述。

在您的代码中,永远无法访问return false;。如果条件计算结果为false,则不会从声明为返回bool的函数返回。这会调用未定义的行为。

不是你代码中的问题,但这看起来很可疑:

char ch;
bool cap;

在初始化变量之前使用变量是一个常见的错误(可能也是UB(。只有当您可以用一些有意义的值初始化变量时,或者如果这不可能,请用一些值初始化变量,例如:,可以避免这种情况

char ch = ' ';
bool cap = false;    

基本上所有的问题都已经提到了。

而且,除了消除明显的错误之外,我还将展示一个更现代的C++解决方案。通过使用现代语言结构,可以避免类似上述的错误。

请参阅:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <cctype>
int main() {
// Open the input file and check, if it could be opened
if (std::ifstream inputFileStream("r:\input.txt"); inputFileStream) {
// Iterate over the characters in the input file and output count of uppercase characters
std::cout << std::count_if(std::istreambuf_iterator<char>(inputFileStream), {}, std::isupper);
}
else {
// If the input file could not be opened, then inform user
std::cerr << "n*** Error: Could not open input filen";
}
return 0;
}