MrMeh
MrMeh

Reputation: 5

Can someone explain the error in this while loop?

So I'm a beginner programmer... and I can't figure out what the problem is in this bit of code I'm writing for a text adventure. All I want it do At the moment is let the user enter a command, and then it converts it to ALLCAPS and prints that out. It should output this:

What shall I do?
pie
Your raw command was: PIE

But instead, it outputs this:

What shall I do?
pie
PIE

...and then it freezes. Here's the code:

#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;
}

I think it may be a problem with the while loop in void command_case(), but I can't figure out exactly what that problem is. I'd appreciate any advice you can give me.

Upvotes: 0

Views: 100

Answers (4)

JarkkoL
JarkkoL

Reputation: 1918

You should remove all cout calls from command_case() function. In fact the whole if-branch in the function is useless and you could just replace it with the following:

command[x]=toupper(command[x]);

For the simplicity you could replace the whole command_case() function with (just remember to #include <algorithm>):

std::transform(userIn.begin(), userIn.end(), userIn.begin(), toupper);

Upvotes: 0

Louis Newstrom
Louis Newstrom

Reputation: 172

The problem is with the x variable in the command_case() function.

When x becomes 3 (and "command[x] points to the null character at the end of "pie") neither islower(command[x]) or isupper(command[x]) are true.

Neither section of the if statement executes, so x stays at 3 forever. Since "userIn.size()+1" is 4, and x never reaches 4, the loop never exits.

A possible solution is remove the "x++" from both sections of the if statement, and have a single "x++" after the if statement. This will increment x during every loop regardless of what character "command[x]" points to.

Upvotes: 1

Kyle Wahl
Kyle Wahl

Reputation: 110

You could easily do something like

void command_case()
{
    for(int i =0; i<userIn.size(); i++)
    {
      userIn[i] = toupper(userIn[i]);
    }
}

then cout<<userIn in the main

Upvotes: 0

laune
laune

Reputation: 31290

One too much:

while(x < userIn.size()+1)

Upvotes: 1

Related Questions