我的字数统计C ++代码在哪里出错

时间:2019-04-28 03:12:53

标签: c++

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

void wordCount(ifstream& in_stream, ofstream& out_stream);

int main()
{
    char inputFile[100];
    ifstream fin;
    ofstream fout;

    cout << "Enter a File name: " << endl;
    cin >> inputFile;

    fin.open(inputFile);
    if (fin.fail())
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }
    wordCount(fin, fout);
    fin.close();
    fout.close();
    return 0;
}

void wordCount(ifstream& in_stream, ofstream& out_stream)
{
    int counter = 0,i;
    char next,last[1];
    in_stream.get(next);

    while (!in_stream.eof())
    {
        if (next == ' ')
            (next >> last[1]);

        for(i = 0; last[i] != '\0'; ++i)
        {   
            if (last[i] == ' ')
                counter++;
        }
        in_stream.get(next);
    }
}

我正在尝试对此进行统计,但无法正常工作 保存的字符很好,但是如果我从记事本中输入类似以下内容的文件,什么也不起作用:

am

工作

如果我输入正常,它将显示0个单词,它将计算为什么会这样?

1 个答案:

答案 0 :(得分:1)

我编辑您的代码,您的意思是这样吗?

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int wordCount(ifstream& in_stream, ofstream& out_stream);

int main()
{
    char inputFile[100];
    ifstream fin;
    ofstream fout;

    cout << "Enter a File name: " << endl;
    cin >> inputFile;

    fin.open(inputFile);
    if (fin.fail())
    {
        cout << "Input file opening failed.\n";
        exit(1);
    }

    int WordCount = wordCount(fin, fout);
    fin.close();
    fout.close();


    return 0;
}

int wordCount(ifstream& in_stream, ofstream& out_stream)
{
    int counter = 0;
    char data[100];

    in_stream >> data;
    while (strlen(data)>0)
    {
        counter++;
        in_stream >> data;
    }
    return counter;
}