如何计算文本文件中的字符数

新手上路,请多包涵

我试图用 C++ 计算文本文件中的字符,这是我到目前为止所拥有的,由于某种原因我得到了 4。即使你里面有 123456 个字符。如果我增加或减少我仍然得到4个字符,请提前帮助和感谢

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const char FileName[] = "text.txt";

int main ()
{
string line;
ifstream inMyStream (FileName);
int c;

if (inMyStream.is_open())
{

     while(  getline (inMyStream, line)){

             cout<<line<<endl;
              c++;
  }
    }
    inMyStream.close();

system("pause");
   return 0;
}

原文由 user836910 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 870
2 个回答

你在数线。

你应该数一下字符。将其更改为:

 while( getline ( inMyStream, line ) )
{
    cout << line << endl;
    c += line.length();
}

原文由 BeemerGuy 发布,翻译遵循 CC BY-SA 3.0 许可协议

C++ 为您提供了一组简单的函数,可用于检索流段的大小。

在您的情况下,我们希望找到文件结尾,这可以通过使用 fstream::seekg 并提供 fstream::end 来完成。

注意 fstream 没有实现结束迭代器重载,这是它自己的结束常量

当我们寻找到文件的末尾时,我们想要使用tellg(在我们的例子中也称为字符计数)来获取流指针的位置。

但我们还没有完成。我们还需要将流指针设置为其原始位置,否则我们将从文件末尾读取。我们不想做的事情。

所以让我们再次调用 fstream::seekg,但这次使用 fstream::beg 将位置设置为文件的开头

std::ifstream stream(filepath);

//Seek to end of opened file
stream.seekg(0, stream.end);
int size = stream.tellg();

//reset file pointer to the beginning of the file
stream.seekg(0, stream.beg);

原文由 Andreas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题