如何计算作为cstring数组输入的单词和行

时间:2016-11-11 11:37:08

标签: c++ dynamic-allocation

该程序应该从用户提供的文本文件中读取一个段落,然后将每一行存储在一个参差不齐的char数组中,并计算段落的单词和行的总数,然后显示结果。

我无法弄清楚为什么线条的数量一直给我3的结果 为什么单词的数量总是缺少2个单词。

请帮助并牢记我最近刚开始学习c ++并不专业。

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

int main()
{
    ifstream infile;//declarations
    char filename[45];
    char **data = 0;
    char **temp = 0;
    char *str = 0;
    char buffer[500], c;
    int numoflines = 0, numofwords = 0;

    cout << "Please enter filename: ";//prompt user to enter filename
    cin >> filename;

    infile.open(filename);//open file

    if (!infile)//check if file was successfully opened
    {
        cout << "File was not successfully opened" << endl << endl;//display error message
        return 0;
    } //end of if

    data = new char*[numoflines];

    while (!infile.eof())
    {
        temp = new char*[numoflines + 1];

        for (int i = 0; i < numoflines; i++)
        {
            infile.getline(buffer, 500);//read line
            for (int i = 0; i < strlen(buffer); i++)//count number of words in line
            {
                c = buffer[i];
                if (isspace(c))
                    numofwords++;
            }
            str = new char[strlen(buffer) + 1];//allocate a dynamic array
            strcpy(str, buffer);
            data[i] = str;
            temp[i] = data[i];
        }//end of for

        infile.getline(buffer, 500);
        for (int i = 0; i < strlen(buffer); i++)//count number of words in line
        {
            c = buffer[i];
            if (isspace(c))
                numofwords++;
        }

        temp[numoflines] = new char[strlen(buffer) + 1];
        strcpy(temp[numoflines], buffer);

        delete[] data;
        data = temp;
        numoflines++;
    }

    cout << "Number of words: " << numofwords << endl;
    cout << "Number of lines: " << numoflines << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:0)

线数的概念仅是观看概念。它没有编码到文件中。以下单个段落可以显示在一行或16行上,具体取决于编辑器窗口的大小:

enter image description here

enter image description here

如果你想指定窗口的字符宽度,可以从中计算行数,但是,段落和wordcount就像你要做的那样好。如果成功打开ifstream infile,则很容易获得:

auto numoflines = 0;
auto numofwords = 0;
string paragraph;

while(getline(infile, paragraph)) {
    numofwords += distance(istream_iterator<string>(istringstream(paragraph)), istream_iterator<string>());
    ++numoflines;
}

cout << "Number of words: " << numofwords << "\nNumber of lines: " << numoflines << endl;

注意:

Visual Studio支持istringstream的内联构造,因此如果您不使用它,则需要在单独的行上构建。