有人能解释一下这个while循环中的错误吗?
Can someone explain the error in this while loop?
所以我是一个初学者程序员…我不知道我为文字冒险游戏编写的这段代码有什么问题。目前我想让它做的是让用户输入一个命令,然后它将其转换为ALLCAPS并打印出来。它应该输出如下内容:
What shall I do?
pie
Your raw command was: PIE
但是,它输出如下:
What shall I do?
pie
PIE
…然后它就冻结了。下面是代码:
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
#include <vector>
using namespace std;
void command_case();
string userIn;
string raw_command;
int x = 0;
int main()
{
while(raw_command != "QUIT")
{
cout << "What shall I do?n";
cin >> userIn;
command_case();
cout << "Your raw command was: " << raw_command << endl;
}
return 0;
}
void command_case()
{
char command[userIn.size()+1];
strcpy(command, userIn.c_str());
while(x < userIn.size()+1)
{
if(islower(command[x]))
{
command[x] = toupper(command[x]);
cout << command[x];
x++;
}
else if(isupper(command[x]))
{
cout << command[x];
x++;
}
}
raw_command = command;
}
我认为这可能是void command_case()
中while循环的问题,但我不能确切地找出这个问题是什么。如果你能给我任何建议,我都很感激。
太多了:
while(x < userIn.size()+1)
问题出在command_case()函数中的x变量。
当x变成3时(并且"command[x]指向"pie"末尾的空字符)islower(command[x])和isupper(command[x])都不为真。
if语句的两个部分都没有执行,所以x永远保持在3。因为"userIn.size()+1"是4,而x永远不会达到4,所以循环永远不会退出。
一种可能的解决方案是从if语句的两个部分中删除"x++",并在if语句之后使用单个"x++"。无论"command[x]"指向哪个字符,它都会在每次循环中增加x。
你可以很容易地像
void command_case()
{
for(int i =0; i<userIn.size(); i++)
{
userIn[i] = toupper(userIn[i]);
}
}
然后cout<<userIn
在主
您应该从command_case()函数中删除所有cout调用。实际上,函数中的整个if分支都是无用的,您可以将其替换为以下内容:
command[x]=toupper(command[x]);
为了简单起见,您可以将整个command_case()函数替换为(请记住#include <algorithm>
):
std::transform(userIn.begin(), userIn.end(), userIn.begin(), toupper);
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- while循环中while循环的时间复杂度是多少
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 擦除while循环中迭代的元素
- 为什么我不能在 while 循环中创建线程?
- 退出简单while循环时出现问题
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 嵌套While循环不起作用(C++问题)
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- 使用 GMP 的 while 循环出现问题
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 为什么在 while 循环中返回表达式不起作用
- 如何使用 do while 循环确定最高值和最低值
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- OpenCV QT,显示视频的帧(不使用while循环)
- 输入循环 while 函数
- c++中的循环(while)
- 为什么这段代码没有循环(while)