1
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

void main()
{
    char info[81];
    string names[5];
    double sales[5][5];
    int count = 0;
    int x = 0;
    ifstream file;
    file.open("sales.txt");

    while(!file.eof())
    {
        x = 0;
        file.getline(info, 80);
        while(info[x] != (char)39)
        {
            while(info[x] != ' ')
            {
                names[count] += info[x];
                x++;
            }
            x++;
            for(int y = 0; y < 4; y++)
            {
                sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5])));
                x += 7;
            }
            x++;
        }
        count++;
    }
}

これを実行すると実行時エラーが発生しますが、正確な理由がわかりません。コンパイラのデバッガにあまり慣れていないので、デバッグに問題があります。

4

2 に答える 2

4

「x」は配列(情報)の境界を超えていると思います。ループに再び入る前に、x が 81 未満であることを確認する必要があります。

元:

while(x < 81 && info[x] != (char)39)
    {
        while(info[x] != ' ')
        {
            names[count] += info[x];
            x++;
        }
        x++;
        for(int y = 0; y < 4; y++)
        {
            sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5])));
            x += 7;
        }
        x++;
    }

とにかく、同じことがループ内の行で発生する可能性があります。入力に特定の長さの文字列が含まれると想定していますが、そうでない場合は、そのエラーが再び発生します。


各行をスペースで分割しようとしている場合は、代わりに (行ごとに) フォーマットされた入力を使用することを検討できます。

        stringStream >> names[count];
        string theNextString;
        stringStream >> theNextString;
        // Process the theNextString, which is the string after the last space (and until the next one)

また、この行は非常にエラーが発生しやすいです。理解しやすいように小さな部分に分割することをお勧めします(また、線の正確な長さにあまり依存しません)。フォーマットされた入力を使用して数値を取得することもできます。

sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5])));

フォーマットされた入力を使用すると、次のようになります

int firstNumber;
stringStream >> firstNumber;

上記は、数字がスペースで区切られている場合にのみ機能することに注意してください。

于 2012-12-14T23:54:39.133 に答える
0

もう一度確認したところ、おそらくコードの次の行であると推測されます。

sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x + 2]) + (.01 *((atoi(&info[x + 4]) * 10) + atoi(&info[x + 5])));

あなたは間違いなく、境界の外に出て、info他の記憶場所に足を踏み入れています。これがメモリ アクセス違反の原因である可能性が高いです。

于 2012-12-14T23:55:01.647 に答える