字符频率重复和重置问题

时间:2015-10-19 00:20:38

标签: c++ switch-statement

我试图根据字符串列表中单词的第一个字母创建一个字符频率计数器,但只要一个值从0变为1,其他计数器就会重置为0.代码看起来像什么像这样:

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

const int MAXIMUMQUANTITY = 400;
struct program
{
int pid;
string program1;
};
struct number
{
    program list[MAXIMUMQUANTITY];
    int numberofdata;
};
int main(void)
{
number alldata;
fstream fREAD;
fREAD.open(text.txt);
int minimum;
cin >> minimum;
int maximum;
cin >> maximum;
if (!fREAD.fail()) {
    alldata.numberofdata = 0;

    while (!ws(fREAD).eof())
    {

        fREAD >> alldata.list[alldata.numberofdata].pid
            >> alldata.list[alldata.numberofdata].program1;

        string program = alldata.list[alldata.numberofdata].program1;
if (minimum <= alldata.list[alldata.numberofdata].pid){
    if (alldata.list[alldata.numberofdata].pid <= maximum){
    int freq1 = 0;
    int freq2 = 0;
    int freq3 = 0;
    int def = 0;
    switch (program[0])
    {                   
    case 'A': freq1++;
        break;
    case 'B': freq2++; 
        break;
    case 'C': freq3++; 
        break;
    default: def++;
        break;
    }
    cout << "category 1: " << freq1 << endl;
    cout << "category 2: " << freq2 << endl;
    cout << "category 3: " << freq3 << endl;
    cout << "category 4: " << def << endl;
}
}
}
}
else
cout << "invalid file" << endl;
}

我希望输出得到这样的结果:

category 1: 1
category 2: 2
category 3: 3
category 4: 4

但我得到了类似的东西:

category 1: 1
category 2: 0
category 3: 0
category 4: 0

category 1: 0
category 2: 1
category 3: 0
category 4: 0

category 1: 0
category 2: 0
category 3: 0
category 4: 1

category 1: 0
category 2: 0
category 3: 0
category 4: 1 etc...

每当更改值时,列表都会重复,更改后的值将遵循列表中的顺序。 例如,如果第一个单词以B开头,第二个单词以A开头,整个列表长度为2个单词,则输出为:

category 1: 0
category 2: 1
category 3: 0
category 4: 0

category 1: 1
category 2: 0
category 3: 0
category 4: 0

1 个答案:

答案 0 :(得分:1)

我认为这是因为你的整数在while循环中并在每个循环中初始化。所以你应该把

int freq1 = 0;
int freq2 = 0;
int freq3 = 0;
int def = 0;

在循环之外。

int freq1 = 0;
int freq2 = 0;
int freq3 = 0;
int def = 0;
 while (!ws(fREAD).eof())

然后你的整数不应该每次都重置为0.

现在它会每次写入,所以你也应该把cout放在while循环的末尾。