有人能解释一下这个while循环中的错误吗?

Can someone explain the error in this while loop?

本文关键字:循环 while 错误 能解释 一下      更新时间:2023-10-16

所以我是一个初学者程序员…我不知道我为文字冒险游戏编写的这段代码有什么问题。目前我想让它做的是让用户输入一个命令,然后它将其转换为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);