I'm trying to make a calcula开发者_运维百科tor in VC++ and even though it runs, it keeps reading memory that I haven't told it to, and I don't know how to make it stop.
#include <iostream>
#include <ctype.h>
int main(){
char equation[4];
equation[3] = '\0'; //string terminator
int result;
bool wantsToContinue = true;
char yesOrNo;
equationPrompt:
std::cout << "Enter Equation: ";
std::cin >> equation;
while(wantsToContinue){
switch(equation[1]){
case '+':
result = int(equation[0]) + int(equation[2]);
break;
case '-':
result = int(equation[0]) - int(equation[2]);
break;
case '*':
result = int(equation[0]) * int(equation[2]);
break;
case '/':
result = int(equation[0]) / int(equation[2]);
break;
}
std::cout << std::endl << "Your answer is " << result << std::endl;
exitPrompt:
std::cout << "Exit? Y/N: ";
std::cin >> yesOrNo;
if(tolower(yesOrNo) == 'n'){
wantsToContinue = true;
goto equationPrompt;
}
else if (tolower(yesOrNo) == 'y')
wantsToContinue = false;
else{
std::cout << std::endl << "Unknown response." << std::endl;
goto exitPrompt;
}
}
return 0;
}
You make it stop by not writing an arcane Frankenstein language mix of C and C++, but instead using real C++ string types:
#include <string>
#include <istream>
#include <iostream>
int main()
{
std::string equation;
std::cin >> equation;
// now equation[0] is the first character
}
Note that int(equation[0])
is almost guaranteed not to be what you think. What you want is something like int x = std::atoi(equation[0]);
or std::strtol()
, but that only works for single digits. Probably much simpler to just stream into an integer, which performs an actual text-to-integer conversion:
int x, y;
std::string operand;
std::cin >> x >> operand >> y;
equation
is an array of 4 char
s.
std::cin >> equation;
reads an arbitrarily long string into that array. Type too much, and it will overflow, stepping on adjacent memory.
As @Kerrek SB says, you're better off using std::string
, which doesn't have that problem.
精彩评论