简体   繁体   English

我的字数 C++ 代码哪里出错了

[英]Where did I go wrong in my code for word count 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);
    }
}

I'm trying to get the word count of this and its not working the chars being saved are fine, but whats not working if I input from notepad a file with something like:我正在尝试获取这个字数,但它不起作用,保存的字符很好,但是如果我从记事本输入一个类似以下内容的文件,则不起作用:

I一世

am

working在职的

it will show 0 words if II type normally it will count the words why is that?如果 II 正常键入它会显示 0 个单词它会计算单词为什么会这样?

I edit your code, Do you mean something like this?我编辑了你的代码,你的意思是这样的吗?

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM