首页 > 解决方案 > 无法添加门以防止我的代码第二次进入 if

问题描述

这是第一个 if,我不希望我的代码第二次输入,所以我添加了一个门。我还有另一个 if,它的条件是计数器等于 3,所以你可以想象,如果我没有第一个 if 的门,我的代码将继续输入第一个 if,因为 2 在 3 之前总是。现在我的问题是什么......每当我在 if 我的代码进入无限循环时添加带有门和行 (gate=0) 的条件时。此外,如果我将门设置为与 1 不同的值,我会得到相同的无限循环。请帮我。

编辑:为了帮助我,您可以在下面找到我的代码的更好示例。谢谢 :)

#include <iostream>
#include <fstream>

using namespace std;

int main() {    
  ifstream file;
  file.open ("file.txt");
  ofstream file1;
  file1.open ("file1.txt");
  char counter = 0; 
  char ch;
  char x;
  string word;
  string word2;
  string word3; 
  int gate = 1;
  word.clear();

  while (file >> std::noskipws >> ch) {         
    if (ch == ' ') {
        ++counter;
    } 
    else if (ch != ' ') {
        counter = 0;
    }

    if ( (counter == 2) && (gate == 1) ) {
        gate = 0;
        x = file.get();

        while ( x != ' ' ) {
            word = word + x;
            x = file.get();
        }
        counter = 1;
        word2 = word;
        word.clear();
        file2 << word1 << " ";      
    }

    if (counter == 3) {
        x = file.get();

        while ( x != ' ' ) {
            word = word + x;
            x = file.get();
        }
        counter = 1;
        word3 = word; 
        word.clear();

        file2 << word3 << endl;
        word3.clear();
        gate = 1;
    }

    if (file.eof()) {
        break;
    }       
  }

  file.close();
  file1.close();

  return 0;
}

标签: c++

解决方案


您的无限循环可能在这里:

  x = file.get();

  while ( x != ' ' ){
    word = word + x;
    x = file.get();
  }

如果到达输入流的末尾,x 将变为 EOF,这与空间不同,因此永远不会离开 while 循环。请检查 EOF 或检查 istream(文件)中的 eofbit。


推荐阅读