gpt4 book ai didi

c++ - 字符频率重复和重置问题

转载 作者:行者123 更新时间:2023-11-28 06:01:28 30 4
gpt4 key购买 nike

我正在尝试根据字符串列表中单词的第一个字母创建一个字符频率计数器,但只要值从 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

最佳答案

我认为这是因为您的整数在 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 循环的末尾。

关于c++ - 字符频率重复和重置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204791/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com