用c ++计算每行文本文件中的单词

时间:2014-02-05 22:32:36

标签: c++

我使用argc,argv和getline打开一个txt文件。我做得很好,但是现在我必须得到每行的字数(以前不知道行数),我必须反过来输出它们。从底线到顶线的含义。任何帮助表示赞赏。此代码输出文件中的字数:

    #include <iostream>
    #include <fstream>
    #include <cstring>
    using namespace std;

    int main(int argc, char *argv[])
    {
        if(argc < 1){   
            cerr << "Usage: " << argv[0] << "filename.txt" << endl; 
        }

            ifstream ifile(argv[1]);
            if(ifile.fail()){
            cerr << "Could not open file." << endl;
            return 1;
            }

        int n;
        ifile >> n;
        cout << n;

        int numberOfWords = 0;  
        string line;
        for(int i = 0; i <=  n; i++){
            getline(ifile, line);
            cout << line << endl;
        }



        size_t i;

        if (isalpha(line[0])) {
            numberOfWords++;
        }

        for (i = 1; i < line.length(); i++) {
            if ((isalpha(line[i])) && (!isalpha(line[i-1]))) {
                numberOfWords++;
            }
        }



        cout<<"The number of words in the line is : "<<numberOfWords<<endl;

        return 0;
}

1 个答案:

答案 0 :(得分:1)

要查找每行的单词数,您可以使用std::getline()迭代每一行,并使用std::stringstream提取每个空格分隔的输入块。然后,您将迭代每个输入块并检查每个字符是否是字母:

int numberOfWords = 0;

for (std::string line, word; std::getline(ifile, line); )
{
    std::istringstream iss(line);

    while (iss >> word)
    {
        bool alpha = true;

        for (char c : word)
            if (!std::isalpha(c)) alpha = false;

        if (alpha) ++numberOfWords;
    }
    std::cout << "Number of words on this line: " << numberOfWords << std::endl;
    numberOfWords = 0;
}