gpt4 book ai didi

c++ - 根据数组中的字符串检查从文件中读入的单词

转载 作者:行者123 更新时间:2023-11-28 03:23:26 24 4
gpt4 key购买 nike

我一辈子都弄不明白为什么这行不通。我必须对文件中的单词列表进行频率检查,在读取它们时,我试图根据字符串数组中的元素检查当前单词,并确保它们在我之前不相等添加它。这是代码:

fin.open(finFile, fstream::in);

if(fin.is_open()) {
int wordArrSize;
while(!fin.eof()) {
char buffer[49]; //Max number chars of any given word in the file
wordArrSize = words.length();

fin >> buffer;

if(wordArrSize == 0) words.push_back(buffer);

for(int i = 0; i < wordArrSize; i++) { //Check the read-in word against the array
if(strcmp(words.at(i), buffer) != 0) { //If not equal, add to array
words.push_back(buffer);
break;
}
}



totNumWords++; //Keeps track of the total number of words in the file
}
fin.close();

这是一个学校项目。我们不允许使用任何容器类,所以我构建了一个结构来处理扩展 char** 数组、推回和弹出元素等。

最佳答案

for(int i = 0; i < wordArrSize; i++) { //this part is just fine
if(strcmp(words.at(i), buffer) != 0) { //here lies the problem
words.push_back(buffer);
break;
}
}

每当当前单词与数组中的第 i 个单词不匹配时,您将输入 if 语句。所以,大多数时候,这将是您进入循环时的第一次迭代。这意味着在循环开始时(在字符串列表中与缓冲区不匹配的第一个单词上)您将缓冲区添加到字符串列表并中断循环。

您应该做的是完成对整个words 数组的检查,然后才将缓冲区添加到数组中。所以你应该有这样的东西:

bool bufferIsInTheArray = false;//assume that the buffered word is not in the array.
for(int i = 0; i < wordArrSize; i++) {
if(strcmp(words.at(i), buffer) == 0) {
//if we found a MATCH, we set the flag to true
//and break the cycle (because since we found a match already
//there is no point to continue checking)
bufferIsInTheArray = true;
break;
}
//if the flag is false here, that means we did not find a match in the array, and
//should add the buffer to it.
if( bufferIsInTheArray == false )
words.push_back(buffer);
}

关于c++ - 根据数组中的字符串检查从文件中读入的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14807558/

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