我对C++和Java非常陌生。我成功地用Java编写了一个简单的计算器,但我的C++翻译却与写入到0时的访问冲突崩溃了。
我知道这表明NULL-pointer有问题,但我不知道在哪里。此外,它有时运行,但有时崩溃,所以我不知道如何跟踪和调试它。
C++
int main() {
bool success = false;
double total = 0.0;
string line = "text";
int in = 1;
do{
cout << "\nPlease enter simple equation\n";
double operands[2];
getline(cin, line);
char input [10];
strcpy_s(input, line.c_str());
int j = 0;
int i = 0;
while(i < sizeof(operands)){
string str = "";
if(input[j] <= 57 && input[j] >= 48 || input[j] == 46){
while(input[j] <= 57 && input[j] >= 48 || input[j] == 46){
str += (input[j]);
if(j+1 < sizeof(input))
j++;
else
break;
}
operands[i] = stod(str);
i++;
}else
j++;
}
for (int o = 0; o < sizeof(input); o++){
switch (input[o]){
case 43:
total = operands[0] + operands[1];
break;
case 45:
total = operands[0] - operands[1];
break;
case 42:
total = operands[0] * operands[1];
break;
case 47:
total = operands[0] / operands[1];
}
}
if(total){
cout << total;
}else{
cout <<"Your input is incorrect! Please enter a valid equation";
cout<< "Ex. 1 + 1";
}
}while(!success);
}Java
Scanner in = new Scanner(System.in);
boolean success = false;
Double total = null;
while (!success) {
System.out.println("\nPlease enter simple equation: ");
try {
double[] operands = new double[2];
String line = in.nextLine();
char[] input = line.toCharArray();
StringBuilder str;
int j = 0;
int i = 0;
while (i < operands.length) {
str = new StringBuilder();
if (input[j] <= 57 && input[j] >= 48 || input[j] == 46) {
while (input[j] <= 57 && input[j] >= 48 || input[j] == 46) {
str.append(String.valueOf(input[j]));
if (j + 1 < input.length) {
j++;
} else
break;
}
operands[i] = Double.parseDouble(str.toString());
i++;
} else
j++;
}
for (int o = 0; o < input.length; o++) {
switch (input[o]) {
case 43:
total = operands[0] + operands[1];
break;
case 45:
total = operands[0] - operands[1];
break;
case 42:
total = operands[0] * operands[1];
break;
case 47:
total = operands[0] / operands[1];
}
}
if (total != null) {
System.out.println(line + " = " + total);
}else{
System.out.println("Your input is incorrect! Please enter a valid equation");
System.out.println("Ex. 1 + 1");
}
} catch (Exception e) {
System.out.println("Your input is incorrect! Please enter a valid equation");
System.out.println("Ex. 1 + 1");
}
}
}发布于 2014-10-21 03:19:57
正如注释中提到的,size of关键字给出了变量(或类型)的大小(以字节为单位)。这导致循环运行了太多次,导致缓冲区溢出。如果将语句更改为
while (i < sizeof(operands) / sizeof (operands[0]) ){这只会使它循环两次。(注意,除非参数是类型,否则不需要将参数放在方括号中)。
下一步应该是了解如何通过使用更多类似于c++的代码来简化程序(例如,不需要复制到char数组,因为可以使用数组访问操作符访问std::string的字符)。
注意:你也应该阅读评论,因为有很多好的建议在那里。
https://stackoverflow.com/questions/26477300
复制相似问题