【问题标题】:c++ variable reassignment gets ignored by code [closed]c ++变量重新分配被代码忽略[关闭]
【发布时间】:2020-06-25 13:37:36
【问题描述】:

我不是专业程序员,但是在获得了一些简单的语言(如 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);
}

所以第一个循环永远不会终止。即使执行了 else 命令,Test2 也永远不会重新分配为 0。这让我大吃一惊——它只是一个简单的 int 赋值运算符。可能的输出如下所示(请注意我仍然遇到第二个问题:内部有空格的字符串被切断。我也将不胜感激任何反馈,即使我尝试一次解决一件事并且这篇文章是不是针对这个问题):

Output example

非常感谢您的考虑!

一切顺利,

一个非常困惑的新手。

【问题讨论】:

  • while(test2 = 1) 试试改成 while(test2 == 1)
  • 你的while条件应该是test2 == 1,你错过了=
  • 打开编译器警告。任何体面的编译器都会很乐意对此发出警告。
  • 您在循环条件中使用了不正确的赋值运算符 while(test2 = 1) 应该是 while(test2 == 1) 您设置正确,但随后在检查中再次分配了一个值而不是被用作比较。
  • 下次请不要发文字图片,而是以文字形式发文字。

标签: c++ variables int variable-assignment


【解决方案1】:

将您的 while 条件更改为 test2 == 1

test2 = 1 是一个赋值,将值设置为 1。

【讨论】:

  • 非常感谢您的快速回复!不幸的是,我没有足够的声誉来立即接受您的回答(似乎有一个计时器),但它确实解决了我的问题。很明显 tbh 现在我看到了。为此浪费了 3 小时的故障排除^^'
  • 为此浪费了 3 小时的故障排除 您需要花 20 分钟来学习如何使用调试器。如果您有一个调试器并且知道如何使用它,那么找到这样的错误将需要几分钟而不是几小时。
  • 我正在使用 Visual Studio,并在调试模式下运行它。但是,我不得不承认我还没有弄清楚如何最有效地使用这个 IDE。输出没有警告我。
  • 在 Visual Studio 中,您需要了解 F10、F11 和 F9 键的作用。这些是最重要的学习。有效的调试从设置断点开始,一次单步执行 1 行代码,同时查看每一步的重要变量,直到看到与预期不符的内容。如果你只是按下播放按钮,你并没有真正从调试器中获得全部好处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
相关资源
最近更新 更多