【问题标题】:Reading number of characters and words in a file读取文件中的字符数和单词数
【发布时间】:2021-07-17 20:33:03
【问题描述】:

我尝试编写一个程序来找出文件中的字符数和单词数:

/*
Write C++ program to count:
Number of characters in a file
Number of words in a file
Number of lines in a file
*/
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
    int countOfCharacters = 0;
    int countOfWords = 0;
    ifstream ins;
    ins.open("hello.txt", ios::in);
    char c;
    while (ins.get(c))
    {
        countOfCharacters += 1;
    }
    cout << "Total Number of characters is " << countOfCharacters << endl;
    ins.seekg(0,ios::beg);
    while(ins.get(c))
    {   cout << "Character is " << c <<endl;
        if (c==' ' || c=='.' || c=='\n'){
        countOfWords+=1;
        }
    }
    cout << "Total number of words in the file is " <<countOfWords <<endl;
    ins.close();
return 0;
}

对于以下输入:

Hi Hello Girik Garg

我得到的输出为:

Total Number of characters is 19
Total number of words in the file is 0

谁能告诉我为什么我没有得到正确的字数?

【问题讨论】:

  • “hello.txt”是否真的包含Hi Hello Girik Garg
  • 是的.. @user306038-----
  • 一次读一个字符会很慢。至少一次读取一行并使用c_str() 上的指针或通过索引旋转字符串。您还可以同时计算字符数和断字数。这里不需要两次通行证。
  • 你的调试代码有什么有用的吗?
  • 对于一个文件的字符数,可以使用文件的大小。寻找到最后,然后读取文件位置。更好的方法是使用操作系统函数来读取文件大小。

标签: c++ file io fstream


【解决方案1】:

当您在第一个读取例程中到达文件末尾时eofbit 标志设置为true,为了能够在不关闭/重新打开它的情况下从同一流中读取,您需要重置它:

//...
ins.clear(); //<--
ins.seekg(0, ios::beg);
//...

话虽如此,您可以按照@YSC 的建议在同一个周期中进行两次计数:

while (ins.get(c))
{        
    countOfCharacters += 1;
    if (c == ' ' || c == '.' || c == '\n')
    {
        countOfWords += 1;
    } 
}

请注意,如果该行不以\n(或'.'/' ')结尾,则不计算最后一个单词,您应该验证流是否确实打开:

if(ins.is_open(){ /*...*/}

【讨论】:

  • 你能告诉我什么是错误标志,为什么我需要清除它们?
  • 顺便说一句,你建议的方式工作正常。
  • @loveofprogramming,当你第一次设置eofbit标志到达文件末尾时,你需要重置它。
  • @loveofprogramming 请注意,如果您在行尾没有换行符,则只会计算 3 个单词
  • @loveofprogramming 这里是一个很好的链接,其中包含有关错误标志及其工作原理的简单说明cplusplus.com/reference/ios/ios/clear
猜你喜欢
  • 1970-01-01
  • 2015-06-09
  • 2011-04-12
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 2014-11-07
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多