【以下回答由 GPT 生成】
问题的原因是在读取文本时,程序会将文本的结尾符(行尾符)也作为一个字符计算进去,导致最后的字符数比实际字符数多了1个。
为了解决这个问题,我们可以对程序进行修改。下面是一个可能的解决方案:
#include <iostream>
#include <fstream>
#include <string>
int countCharacters(const std::string& filename) {
std::ifstream file(filename);
if (!file) {
std::cerr << "无法打开文件: " << filename << std::endl;
return -1;
}
int count = 0;
std::string line;
while (std::getline(file, line)) {
count += line.length();
}
return count;
}
int main() {
std::string filename;
std::cout << "请输入文件名: ";
std::cin >> filename;
int count = countCharacters(filename);
if (count >= 0) {
std::cout << "字符数: " << count << std::endl;
}
return 0;
}
这个解决方案使用了std::getline()
函数逐行读取文本,并使用line.length()
获取每行的字符数。通过这种方式,我们可以避免将结尾符也计算在内。
请注意在使用时,确保文本文件存在并且程序具有读取文件的权限。
【相关推荐】