如何读取和计算输入文件中的单词,使用C ++计算和打印每个单词的字母数量?

时间:2016-06-26 18:09:53

标签: c++ eclipse string macos file

我是编程方面的新手,并且有一项任务要求我创建一个程序,该程序将读取带有单词列表的文本文件,计算单词的总量和每个单词的字母数量并打印出输出具有x个字母数量的文件,按字母数量从1个字母单词到13个字母单词。

当我创建我的函数并尝试让它读取文本文件中的单词时,它不允许我使用inFile >> word;来读取它们的长度。

我收到错误:

  

"二进制表达式的操作数无效"。

其他同学使用此命令没有遇到任何麻烦。我在OS X El Capitan上使用Eclipse Mars.1。

我得到的另一个错误是我的开关功能,它评估第一种情况但不适用于以下情况。在这种情况下,我收到以下错误消息:

  

" '壳体'声明不在Switch声明"。

提前致谢!

void Words_Statistics(std::ifstream & fin, std::ofstream & fout, std::string inFile, std::string outFile)
    {

    // Variable Declaration
    inFile="words.txt";
    outFile="Words_Satistics.txt";
    string word;
    int totalWords=0;
    int lettersQuantity;
    int un, deux, trois, quatre, cinq, six, sept, huit, neuf, dix, onze, douze, treize, otre;
    un = deux = trois = quatre = cinq = six = sept = huit = neuf = dix = onze = douze = treize = otre=0;

    // Open input file to read-in
    fin.open(inFile);
        if(fin.fail())
        {
            cout << inFile << " Failed to open file."<< endl;
            exit (1);
        }
        do {
            (inFile >> word);
            lettersQuantity = int (sizeof(word));
            totalWords++;
            lettersQuantity+=lettersQuantity;

                switch (lettersQuantity)
                    case 1:
                        un++;
                        break;
                    case 2:
                        deux++;
                        break;
                    case 3:
                        trois++;
                        break;
                    case 4:
                        quatre++;
                        break;
                    case 5:
                        cinq++;
                        break;
                    case 6:
                        six++;
                        break;
                    case 7:
                        sept++;
                        break;
                    case 8:
                        huit++;
                        break;
                    case 9:
                        neuf++;
                        break;
                    case 10:
                        dix++;
                        break;
                    case 11:
                        onze++;
                        break;
                    case 12:
                        douze++;
                        break;
                    case 13:
                        treize++;
                        break;
                    default:
                        otre++;
                        break;
        }
        while (!fin.eof());

    int avg = lettersQuantity / totalWords;
}

1 个答案:

答案 0 :(得分:0)

此处inFile >> wordinFilewordstd::string,因此将operator>>应用于他们是不合理的(您毕竟不能正确移动字符串,这会产生意想不到的结果:))。

您可能需要fin >> word,其中fin是您打开的文件:)

switch语句需要括号:

switch (lettersQuantity)
{ //Note bracket
case 1: //....
//....
}

在一个不相关的说明中,sizeof(word)并没有按照您的想法行事。它得到word的实际大小,这不是word个字符的数量。您可以使用word.length():)