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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10712117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:22:03  来源:igfitidea点击:

how to count the characters in a text file

c++visual-c++

提问by user836910

im trying to count the characters inside a text file in c++, this is what i have so far, for some reason im getting 4. even thou i have 123456 characters in it. if i increase or decrease the characters i still get 4, please help and thanks in advance

我正在尝试用 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;
}

回答by BeemerGuy

You're counting the lines.
You should count the characters. change it to:

你在数线。
你应该计算字符。将其更改为:

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

回答by sbabbi

There are probably hundreds of ways to do that. I believe the most efficient is:

可能有数百种方法可以做到这一点。我认为最有效的是:

    inMyStream.seekg(0,std::ios_base::end);
    std::ios_base::streampos end_pos = inMyStream.tellg();

    return end_pos;

回答by Brenden

this is how i would approach the problem:

这就是我将如何解决这个问题:

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

using namespace std;


int main () 
{
string line;
int sum=0;
ifstream inData ;
inData.open("countletters.txt");

while(!inData.eof())
{
getline(inData,line);

    int numofChars= line.length();
    for (unsigned int n = 0; n<line.length();n++)
    { 
    if (line.at(n) == ' ')
    {
    numofChars--;
    }
    }
sum=numofChars+sum;
}
cout << "Number of characters: "<< sum << endl;
    return 0 ;
}

回答by shengy

First of all, you have to init a local var, this means: int c = 0;instead of int c;

首先,你必须初始化一个本地变量,这意味着: int c = 0;而不是 int c;

I think the old and easy to understand way is to use the get()function till the end char EOF

我认为古老且易于理解的方法是使用该get()函数直到结束字符EOF

    char current_char;
    if (inMyStream.is_open()) 
        {

            while(inMyStream.get(current_char)){

                if(current_char == EOF)
                {
                    break;
                }
                c++;
            }
        }

Then cwill be the count of the characters

然后c将是字符数

回答by Subbu

I found out this simple method , hope this helps

我发现了这个简单的方法,希望对您有所帮助

while(1)
    {
        if(txtFile.peek() == -1)
            break;
        c = txtFile.get();
        if(c != txtFile.eof())
                    noOfChars++;
    }

回答by Richard J. Ross III

Just use good old C FILE pointers:

只需使用旧的 C FILE 指针:

int fileLen(std::string fileName)
{
    FILE *f = fopen(fileName.c_str(), "rb");

    if (f ==  NULL || ferror(f))
    {
        if (f)
            fclose(f);

        return -1;
    }

    fseek(f, 0, SEEK_END);
    int len = fell(f);

    fclose(f);

    return len;
}

回答by Martin Melichar

This works for sure, it is designed to read character by character.

这肯定有效,它旨在逐个字符地读取。

It could be easily put into a class and you may apply function for every char, so you may check for '\n', ' ' and so on. Just have some members in your class, where they can be saved, so you may only return 0 and use methods to get what exactly you want.

它可以很容易地放入一个类中,您可以为每个字符应用函数,因此您可以检查 '\n'、' ' 等。只要在你的班级中有一些成员,他们可以被保存在那里,所以你可能只返回 0 并使用方法来获得你想要的东西。

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

unsigned long int count(std::string string)
{
    char c;
    unsigned long int cc = 0;

    std::ifstream FILE;
    FILE.open(string);
    if (!FILE.fail())
    {
        while (1)
        {
            FILE.get(c);
            if (FILE.eof()) break;
            cc++; //or apply a function to work with this char..eg: analyze(c);
        }
        FILE.close();
    }
    else
    {
        std::cout << "Counter: Failed to open file: " << string << std::endl;
    }

    return cc;
};

int main()
{
    std::cout << count("C:/test/ovecky.txt") << std::endl;

    for (;;);

    return 0;
}