This is for school
I'm using the same implementation that I used for a previous project where I just make a terminate variable then break out of my loop when that terminate variable is read. However, for this program that I wrote, my exit statement just reads in the user input and continues with the program. I have tried both a while loop and do while loop.
Here is my program
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;
}
There is two things which interrupts work of your code
std::transform(terminate.begin(), terminate.end(), terminate.begin(),::toupper); //Extra stuff makes it not case sensitive
First of all the logical issue. You perform operation on predefined string terminate but you don't change the user input string input . In fact you can replace your
std::string terminate = "end";
std::transform(terminate.begin(), terminate.end(), terminate.begin(),::toupper); //Extra stuff makes it not case sensitive
by one row
std::string terminate = "END";
And next thing is you change the case of row before reading loop so it can't modify the user input, it only defines initial state of string. Thus the position and target of the string modification needs to be modified:
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;
}
I located the input modification after checkBalance(input) since I'm not sure about modifications which it can do for the input . In fact the most logical position of the input case conversion is directly after reading the string, ie after
std::cin >> input;
One more note. Your initial code should exit for END input (ie uppercase).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.