c ++变量重新分配被代码忽略

c++ variable reassignment gets ignored by code

我不是专业程序员,但在使用 python 或 matlab 等简单语言获得一些经验后,我需要用 C++ 编写一个小程序。为此,我尝试读取用户输入,直到用户输入一些合理的东西——然而,由于我的控制变量(test2)从未被重新分配,这个循环永远不会终止,即使输入了相应的代码块。让我详细解释一下:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Header.h"

using namespace std;

int test2; //variable to stay 1 until user has entered suitable input
string input2[2]; //storage for input strings

int MinimalTest() {
  test2 = 1; //control variable is set one
  cout << "Enter a string." << endl;
  do {
     //we will enter a string at least once, and we exit this loop only when the input is suitable
      std::string line; //complicated input part - a simple getline() command led to weird behaviour 
      std::getline(std::cin, line);
      std::stringstream linestream(line);
      linestream >> input2[i];
      cout << "input: " << input2[i] << " test: " << test2 << "input bool: " << input2[i].empty() << endl; //this is just for troubleshooting

      if (input2[i].empty()) {
        //if the user entered an empty string, he needs to do it again
          cout << "Your string is empty. Please enter a valid string (non-empty)." << endl;
      }
      else {
        //if he entered a valid string, we can continue with the next input
          cout << "I am here." << endl; //This is for trouble shooting. This code block is entered and executed since this gets printed.
          test2 = 0;// this gets ignored for some reason. Hence, the loop never terminates.
      }
  }(while (test2 = 1);
}

所以第一个循环永远不会终止。 Test2 永远不会被重新分配为 0,即使执行了 else 命令。这让我大吃一惊——它只是一个简单的 int 赋值运算符。可能的输出看起来像这样(请注意我仍然遇到第二个问题:内部带有 space 的字符串被截断。我也很感激对此的任何反馈,即使我尝试一次解决一件事而这个post不是针对这个问题的):

Output example

非常感谢您的考虑!

祝一切顺利,

一个很迷茫的新手。

更改您的 while 条件以测试 2 == 1

test 2 = 1 是一个赋值,将值设为 1。