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

标签 c++ arrays input char duplicates

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

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/

相关文章:

c++ - 是否有可能我有一个类的前向声明,而不是在头文件中使它们成为引用或指针

c++ - 如何删除由 union 成员及其隐式删除的成员函数引起的代码重复?

javascript - 如何使用 JavaScript 动态删除换行符和文本输入?

c++ - 使用 C++ 中提供的默认值获取字符串输入

assembly - 缓冲输入如何工作

c++ - IWebBrowser2.Document 不返回 IHTMLDocument2

java - 创建一个内联对象并作为参数传递

javascript - 如何使用 Javascript 获取多个对象数组的每种组合

c++ - 为什么无法在 C++ 中创建引用数组?

c++ - C++中使用变量初始化数组