C++为什么我的编译器成功了,但我的计算机给出了调试错误?

C++ why does my compiler succeed but my computer gives a debug error?

本文关键字:我的 错误 计算机 调试 为什么 编译器 成功 C++      更新时间:2023-10-16

所以我在尝试运行程序时完成了编译器的错误,现在从我所看到的情况来看,编译器成功了,但控制台是空白的,除了文件位置和弹出一个错误窗口,上面写着"调试错误![程序文件位置名称] abort(( 已从 Visual C++ 运行时库中调用Microsoft。我不知道此错误是由我的计算机还是代码引起的。如您所知,我对此非常陌生,并且不知道如何诊断编译器未给出的问题。

下面是收到此错误的程序。设计用于最终在输入为罗马数字的两个值之间执行操作。

#include <iostream>
#include <cmath>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

int conNtoD(char val)
{
int number;
if (val == 'M')
{
number = 1000;
}
else if (val == 'D')
{
number = 500;
}
else if (val == 'C')
{
number = 100;
}
else if (val == 'L')
{
number = 50;
}
else if (val == 'X')
{
number = 10;
}
else if (val == 'V')
{
number = 5;
}
else if (val == 'I')
{
number = 1;
}
else
{
number = 0;
}


return number;
}
int get_data(string numerone)
{
int pos = 0;
char val;
int totalval1=0;
int cou = numerone.length();

while (pos <= cou)
{
int number=0;
val= numerone.at(pos);
number = conNtoD(val);
totalval1 = totalval1 + number;

pos++;

}


return totalval1;
}
int get_data2 (string numertwo)
{
int pos = 0;
char val;
int totalval2=0;
int cou = numertwo.length();
while (pos <= cou)
{
int number = 0;
val = numertwo.at(pos);
number = conNtoD(val);
totalval2 = totalval2 + number;
pos++;

}


return totalval2;
}



int main()
{ 
string numerone;
string numertwo;
char op;
int x = 0;
int pos = 0;
int pos2 = 0;
ifstream numerals("Numerals.txt");
while (numerals >> numerone >> numertwo >> op)
{ 
int totalval1= get_data(numerone);
int totalval2= get_data2(numertwo);

cout << numerone << " " << numertwo << " " << op << endl;
cout << totalval1 << " and " << totalval2 << endl;
} 

}

这是你的错误

int cou = numerone.length();
...
while (pos <= cou)

cou是字符串的长度。 例如,如果您的字符串是"MM",则长度为 2。 字符串字符的有效索引范围从 0 到(包括length-1(。 也就是说,0 和 1 是长度为 2 的字符串字符的有效索引。

但是,while 循环正在评估从 0 到长度(包括长度(pos。 当您尝试访问字符串MM的位置 2 时,at方法将引发异常。

简单的解决方法是少迭代一个

while (pos < cou)

仅此而已。