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

标签 c++ variables int variable-assignment

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




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

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

关于c++变量重新分配被代码忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60672127/

相关文章:

c++ - 我应该如何在 C++ 中实现这些 vector ?它与 vector 有关的纬度和经度

java - 按字母顺序重新排序字符串变量

c++ - 为什么打印16而不是17并且变量不增加?

c - 有没有一种可移植的方法来定义 INT_MAX?

c - 1 个主程序中的 2 个功能(Visual Studio 2013)

c++ - 为什么 STL 需要一个临时迭代器变量来编译它?

长度为100的C++循环队列类

c++ - Boost::GIL:读取具有 alpha channel 的 *.png 图像缺少抗锯齿功能

css - Sass Mixin 参数 - 阻止 Sass 转换分数(例如 1/3 转换为 0.33333)?

c - 在c中动态增加数组(int *)的大小