尝试读取文件并将其输出为行,并计算字符,行和非空格字符以及单词的数量。我想我快完成了,但我不知道该如何计算字数。另外,它会切掉每行的第一个字母,但在我运行它时会先切开。

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

using namespace std;

int main()
{
    int line_number = 0;
    char words;
    int number_of_spaces = 0;
    int number_of_lines = 0;
    int number_of_characters = 0;
    int number_of_words = 0;
    int count = 0;
    char character;
    string word;
    int n = 0;
    string line;
    ifstream myFile;
    string file;
    cout <<"Enter file name: ";
    getline(cin,file);


    myFile.open(file.c_str());
    char output[100];



    if(myFile.is_open())
    {

        cout << " " << endl;

        while( getline ( myFile, line ) )
        {
            line_number += 1;
            cout << "Line: " << line_number << " ";
            cout << line << endl;

            number_of_characters += line.length();

            for (int i = 0; i < line.length(); i++)
            {
                if(line[i] == ' ' || line[i] == '/t')
                {
                    number_of_spaces++;
                }
            }

            myFile.get(character);
            if (character != ' ' || character != '/n')
            {
                number_of_lines += 1;
            }


        }




        cout << " " << endl;
        cout << number_of_characters << " characters, " << endl;
        cout << number_of_characters - number_of_spaces << " non whitespace characters, " << endl;
        cout << number_of_words << " words, " << endl;
        cout << number_of_lines << " lines." << endl;

    }

    myFile.close();

    system("Pause");
    return 0;
}

最佳答案

您可以使用>>运算符逐字读取文件。所以这段代码应该可以工作:

std::string word;
int counter = 0;
while (myFile >> word)
{
    counter++;
}

关于c++ - 读取文件并计数单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38084925/

10-12 03:01