我正试着用VC++做一个计算器,即使它在运行,它仍然在读取我没有告诉它的内存,我不知道如何让它停止。
#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;
}发布于 2011-08-17 05:47:20
通过使用真正的C++字符串类型,而不是编写神秘的C和C++混合的科学怪人语言,可以让它停下来:
#include <string>
#include <istream>
#include <iostream>
int main()
{
std::string equation;
std::cin >> equation;
// now equation[0] is the first character
}请注意,几乎可以保证int(equation[0])不是您想的那样。你想要的是像int x = std::atoi(equation[0]);或std::strtol()这样的东西,但它只适用于个位数。可能更简单的只是流到一个整数,它执行一个实际的文本到整数的转换:
int x, y;
std::string operand;
std::cin >> x >> operand >> y;发布于 2011-08-17 05:51:25
equation是一个由4个char组成的数组。
std::cin >> equation;将任意长的字符串读入该数组。键入太多,它将溢出,踏入相邻的内存。
正如@Kerrek SB所说,你最好使用std::string,它没有这个问题。
https://stackoverflow.com/questions/7085421
复制相似问题