gpt4 book ai didi

c++ - 变量 'equation' 周围的堆栈已损坏

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:44 27 4
gpt4 key购买 nike

我正在尝试用 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;
}

最佳答案

您可以通过不编写 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;

关于c++ - 变量 'equation' 周围的堆栈已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7085421/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com