0

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

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** 数组、推回和弹出元素等。

4

2 回答 2

1

我认为你的代码words.push_back(buffer);应该在 for 循环之外。放置一个标志以检查是否在 for 循环内的数组中找到缓冲区,并根据标志将其添加到 for 循环外的数组中

于 2013-02-11T07:25:43.397 回答
1
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;
    }
}

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

您应该做的是完成检查整个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);
}
于 2013-02-11T07:34:03.437 回答