【发布时间】: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 赋值运算符。可能的输出如下所示(请注意我仍然遇到第二个问题:内部有空格的字符串被切断。我也将不胜感激任何反馈,即使我尝试一次解决一件事并且这篇文章是不是针对这个问题):
非常感谢您的考虑!
一切顺利,
一个非常困惑的新手。
【问题讨论】:
-
while(test2 = 1) 试试改成 while(test2 == 1)
-
你的while条件应该是
test2 == 1,你错过了=。 -
打开编译器警告。任何体面的编译器都会很乐意对此发出警告。
-
您在循环条件中使用了不正确的赋值运算符 while(test2 = 1) 应该是 while(test2 == 1) 您设置正确,但随后在检查中再次分配了一个值而不是被用作比较。
-
下次请不要发文字图片,而是以文字形式发文字。
标签: c++ variables int variable-assignment