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

时间:2018-10-09 00:43:37

标签: c++

因此,在尝试运行程序时,我已解决了编译器的错误,现在,从我所看到的情况来看,它可以在编译器中成功运行,但是除了文件位置以外,控制台为空白,并弹出一个错误窗口,显示“调试错误!已从Microsoft Visual c ++运行时库调用[程序文件位置名称] abort()。我不知道此错误是由我的计算机或代码或什么引起的。如您所知,我对此很陌生,也没有丝毫线索来诊断编译器未给出的问题。

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

#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;

    } 



}

1 个答案:

答案 0 :(得分:2)

这是你的错误

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

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

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

简单的解决方法是减少迭代次数

{{1}}

仅此而已。