【问题标题】:(C++) fstream win32 exception occured in title.exe [6284](C++) 在 title.exe 中出现 fstream win32 异常 [6284]
【发布时间】:2015-10-22 19:46:22
【问题描述】:

所以我做了以下算法来解决一个问题,但是我不明白为什么当我使用 fstream 而不是 iostream 时它会崩溃。例如,当我使用较小的数字(输入例如:1 4 5)时,它与 fstream 完美配合,但如果我使用一些较大的输入数字(例如:3 987654300 210),它会显示“进程返回 -1073741819 (0xC0000005)”。如果我使用 iostream,即使是 9 位输入,它也能很好地工作。

是的,我将 parola.in 和 parola.out 与 .cpp/.exe 放在同一个文件夹中,而 .in 包含输入数字和所有内容。

忽略算法和cmets,请注意“fout”和“fin”的使用。

#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    ifstream fin("parola.in");
    ofstream fout("parola.out");

    int a,b,k; //VARIABILE ORIGINALE
    int ord=1; //NUMARUL DE ORDINE AL VECTORILOR
    int cifa=0,cifb=0; //NUMARUL DE CIFRE AL NUMERELOR A SI B

    int nrA[18],nrB[10]; //VECTORII CE CONTIN CIFRELE NUMERELOR A SI B
    int temp[9]; //VECTORUL CE CONTINE CIFRELE NR. A IN ORDINE INVERSA

    fin>>k>>a>>b;

    while (a>0)
    {
        temp[ord]=a%10;
        a/=10;
        ord++;
        cifa++;
    }

    ord=1; //RESET NR ORDINE

    while (b>0)
    {
        nrB[ord]=b%10;
        b/=10;
        ord++;
        cifb++;
    }

    for (int topkek=1; topkek<=cifa; topkek++)
    {
        nrA[topkek]=temp[cifa+1-topkek]; //ORDONAREA CIFRELOR LUI A CRESCATOR, IN VECTORUL nrA
    }

    for (int zomtan=1; zomtan<=k; zomtan++)
    {
        fout<<nrA[zomtan];
        nrA[zomtan]=-1;
    }
    fout<<nrB[1];
    nrB[1]=-1;
    for (int zomtan2=cifa+1; zomtan2<=18; zomtan2++)
    {
        nrA[zomtan2]=-1;
    }

    for (int zomtan3=cifb+1; zomtan3<=10; zomtan3++)
    {
        nrB[zomtan3]=-1;
    }

    for (ord=1; ord<=9; ord++)
    {
        if (nrA[ord+k]!=-1)
        {
            fout<<nrA[ord+k];
        }
        if (nrB[ord+1]!=-1)
        {
        fout<<nrB[ord+1];
        }
    }
    return 0;
}

【问题讨论】:

  • 您不妨创建一个Minimal, Compilable and Verifiable Example(简称 MCVE),它可以帮助人们更轻松地理解问题所在。
  • 如果您认为问题只是改变了流类型,那您就大错特错了。您很可能正在越界访问数组元素,从而导致发生未定义的行为。更改流类型只会将错误暴露给您。
  • 使用std::arraystd::vector 使用调试器捕获缓冲区溢出。
  • 是的,我在这段代码中非常糟糕...我不得不将 nrA 向量从 [18] 容量扩展到 [19]...我不敢相信我正在尝试访问向量中的一些未分配的插槽。但有趣的部分是为什么它可以完美地与 iostream 配合使用。
  • 我知道 iostream 和 fstream 根本不修改算法,这就是为什么它这么奇怪。

标签: c++ winapi exception


【解决方案1】:

问题可能是因为,我想,您使用基于 1 的数组而不是基于 propper 0 的数组

for (int zomtan2=cifa+1; zomtan2<=18; zomtan2++)
{
    nrA[zomtan2]=-1;
}

问题总会出现,因为你写了zomtan2&lt;=18

你的数组声明是int nrA[18],我之前说过总是会导致问题。

这些错误在你的代码中无处不在,所以我建议你重写程序

【讨论】:

  • 他也在while循环中的数组末尾进行9位输入
  • 我知道。我只是想把它说出来,以防你想把它添加到答案中。
猜你喜欢
  • 2012-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多