air*_*n19 0 c++ memory arrays memory-leaks calculator
我正在尝试用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;
}
Run Code Online (Sandbox Code Playgroud)
你不要写一个C和C++的神秘的科学怪人语言混合,而是使用真正的C++字符串类型:
#include <string>
#include <istream>
#include <iostream>
int main()
{
std::string equation;
std::cin >> equation;
// now equation[0] is the first character
}
Run Code Online (Sandbox Code Playgroud)
请注意,int(equation[0])几乎可以保证不会出现您的想法.你想要什么是一样的东西int x = std::atoi(equation[0]);或std::strtol(),但仅适用于个位数.简单地流入一个执行实际文本到整数转换的整数可能要简单得多:
int x, y;
std::string operand;
std::cin >> x >> operand >> y;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
349 次 |
| 最近记录: |