【问题标题】:Checking a word read in from a file against strings in an array对照数组中的字符串检查从文件中读入的单词
【发布时间】:2013-01-26 06:49:14
【问题描述】:

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

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

【问题讨论】:

  • @Alex,他到底为什么不应该问作业问题?
  • @SingerOfTheFall 我以为他们被禁止了?
  • @Alex,不,我们只是不再用homework 标记问​​题。家庭作业问题与任何其他问题没有什么不同。您可以在homework 标签信息中了解它
  • @SingerOfTheFall 够公平的。我不能再编辑我的评论了,所以我将删除,因为其中一个答案澄清了我试图指出的内容。

标签: c++ arrays input char duplicates


【解决方案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;
    }
}

每次当前单词与数组中的ith 单词不匹配时,您都将输入您的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);
}

【讨论】:

  • 成功了,谢谢!我不知道为什么我没有早点意识到这一点。一开始我的逻辑似乎是完全证明的
【解决方案2】:

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

【讨论】:

  • 试过了,不行。这与 strcmp() 采用两个 char* 没有任何关系吗?缓冲区[49] 在传递时应该衰减为一个指针,除非我遗漏了一些东西。真的没有其他解释......这张支票应该被剪掉并晾干啊
  • 你确定。我的意思是修改在上面的答案中完全编码你试过那个答案吗?在您的代码中,如果任何一个单词与单词中的一个单词不同,则将其添加到数组中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多