【问题标题】:About Exception Grown关于异常成长
【发布时间】:2018-05-13 05:43:34
【问题描述】:

我是编程初学者。最近,我写了一个程序,从字符串 date 中提取日、月、年并转换为 int 并分配给数组的元素。但是VS在编译时返回一个我不太明白的错误。请帮我解释一下! 提前致谢! 我的程序

using namespace std;

int a[2];
int j = 0;
string str_date;
string str_date_sub;

void get_date()
{
    if (str_date.find('/') == str_date.npos)
    {
        stringstream ss(str_date);
        ss >> a[j];
    }
    for (int i = 0; i <= str_date.length(); i++)
    {
        if (str_date[i] == '/')
        {
            str_date_sub = str_date.substr(0, i - 1);
            str_date.erase(0, i + 1);
            stringstream ss(str_date_sub);
            ss >> a[j];
            j++;
            break;
        }
    }
    get_date();
}

int main()
{
    cout << "Please input the date DD/MM/YYYY:\n";
    str_date = "12/05/1234";
    get_date();
    cout << a[1];
    system("pause");
    return 0;
}

编辑: 错误在这里

ss >> a[j];

Exception thrown at 0x5B03297A (msvcp140d.dll) in Project6.exe: 0xC0000005: Access violation writing location 0x01116890.

【问题讨论】:

  • 错误是什么?
  • 对不起,错误在这里 ss >> a[j];

标签: c++


【解决方案1】:

三个错误:

日期中有三个标记所以

int a[2];

需要

int a[3];

下一个

str_date_sub = str_date.substr(0, i - 1);

第二个参数是子串的长度,所以

str_date_sub = str_date.substr(0, i);

比较合适。

最后,在get_date

get_date();

总是被调用,导致不受控制的递归。最终程序耗尽了自动存储,之后所有的赌注都被取消了。如果要解析的字符串更多,您只想重新输入该函数。最简单的解决方法是在

的末尾放置 return
if (str_date.find('/') == str_date.npos)
{
    stringstream ss(str_date);
    ss >> a[j];
    return; // right here
}

但为什么要停在那里?

if (str_date.find('/') == str_date.npos)

找到/的位置,那为什么

for (int i = 0; i <= str_date.length(); i++)

嗯。制造4个错误。 i &lt;= str_date.length() 将走出str_date 的界限。

无论如何,这个循环没有意义。你可以

auto pos = str_date.find('/');

然后在函数的其余部分使用pos

您也可以消除所有全局变量,但 Deadpool 已开启,所以我要退出。

【讨论】:

    【解决方案2】:

    当你达到这个条件时:(str_date.find('/') == str_date.npos) 变量j 包含值 2。在这种情况下你调用ss &gt;&gt; a[j];,即ss &gt;&gt; a[2];,它试图访问大小为 2 的数组的第三个元素.它是数组边界之外的访问。你必须声明int a[3]

    此外,当j 加入 2 时,您必须中断递归,否则不正确的日期“12/05/12/1234”将再次使您的程序崩溃。最后在条件下移动调用get_date()

    if (j < 3)
      get_date();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2017-12-11
      • 2010-12-25
      • 2013-06-22
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多