这是给学校的
我使用的实现与我在以前的项目中使用的实现相同,在该实现中,我只创建一个终止变量,然后在读取该终止变量时跳出循环。但是,对于我编写的这个程序,我的退出语句只是读入用户输入并继续执行该程序。我已经尝试了 while 循环和 do while 循环。
这是我的程序
int main() {
std::string input;
std::string terminate = "end";
std::transform(terminate.begin(), terminate.end(), terminate.begin(),::toupper); //Extra stuff makes it not case sensitive
std::cout << "This program checks for a balanced expression" << std::endl << "Enter 'end' to end the program" << std::endl;
while(input != terminate){
std::cout << "Enter Expression: ";
std::cin >> input;
if(checkBalance(input))
std::cout << input << " " << "is balanced" << std::endl;
else
std::cout << input << " " << "is not balanced" << std::endl;
}
return 0;
}
有两件事会中断您的代码工作
std::transform(terminate.begin(), terminate.end(), terminate.begin(),::toupper); //Extra stuff makes it not case sensitive
首先是逻辑问题。您对预定义的字符串执行操作终止但不更改用户输入字符串input。事实上,你可以更换你的
std::string terminate = "end";
std::transform(terminate.begin(), terminate.end(), terminate.begin(),::toupper); //Extra stuff makes it not case sensitive
一排
std::string terminate = "END";
接下来是在读取循环之前更改行的大小写,因此它无法修改用户输入,它仅定义字符串的初始状态。因此需要修改字符串修改的位置和目标:
int main() {
std::string input;
// Replace two initial rows by one with the same result
std::string terminate = "END";
std::cout << "This program checks for a balanced expression" << std::endl << "Enter 'end' to end the program" << std::endl;
while(input != terminate){
std::cout << "Enter Expression: ";
std::cin >> input;
if(checkBalance(input))
std::cout << input << " " << "is balanced" << std::endl;
else
std::cout << input << " " << "is not balanced" << std::endl;
// Modify user input to upper case for possibility of successful check on next while loop
std::transform(input.begin(), input.end(), input.begin(),::toupper); //Extra stuff makes it not case sensitive
}
return 0;
}
我在checkBalance(input)之后找到了输入修改,因为我不确定它可以对input进行哪些修改。实际上输入大小写转换最合乎逻辑的位置是直接读取字符串之后,即之后
std::cin >> input;
再一记。您的初始代码应该为END输入(即大写)退出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句