编写了一个可以读入文本并输出文本有多少字符的程序

img

img

img

img


编写了一个可以读入文本并输出文本有多少字符的程序,但文本字符只有22个,为什么显示23个,而且就算读取换行符的话也是22+3个,多出来的1个代表什么。

【以下回答由 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()获取每行的字符数。通过这种方式,我们可以避免将结尾符也计算在内。

请注意在使用时,确保文本文件存在并且程序具有读取文件的权限。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^
  • 您的文本可是四行哦,第一行是空行,只有一个换行符

    三行文本样子

    img



    四行文本样子

    img