0

次のように、ヘッダー ファイルで配列を宣言しました。

private:
   int frames[10];

そして、次のようにクラス コンストラクターに値を割り当てます。

file.open(File);
if(file.is_open())
{
    std::string line;
    getline(file, line);
    std::string param[10];
    std::stringstream stream(line);
    int n=0;
    while(!stream.eof())
    {
        getline(stream, param[n], '$');
        frames[n] = atoi(param[n].c_str());
        n++;
    }
    file.close();
}

後で、この配列は関数で使用されます。

currentFrame++;
if(frames[currentAnimation] <= currentFrame)
{
    currentFrame = 0;
}

コードを実行すると、セグメンテーション エラーが発生し、gdb は次のように返します。

Program received signal SIGSEGV, Segmentation fault.
0x0000000000402c22 in Sprite::update (this=0x7ffff6efe678 <main_arena+88>) at Sprite.cpp:93 93              
if(frames[currentAnimation] <= currentFrame)
(gdb) bt
#0  0x0000000000402c22 in Sprite::update (this=0x7ffff6efe678 <main_arena+88>) at Sprite.cpp:93
#1  0x0000000000401fcb in main (argc=1, argv=0x7fffffffeb88) at main.cpp:146

どこが間違っているのかわかりません。エラーはここのどこかにあると思います。たくさんのコードがあるので、すべてのコードを掲載することはできませんが、具体的な情報が必要な場合は、お問い合わせください。

事前にどうもありがとうございました。

4

3 に答える 3

3

これを試して

private:
   std::vector<int> frames;


file.open(File);
if(file.is_open())
{
    std::string line;
    getline(file, line);
    std::string param;
    std::stringstream stream(line);
    while(getline(stream, param, '$'))
        frames.push_back(atoi(param.c_str()));
    file.close();
}

currentFrame++;
if( currentAnimation < frames.size() && frames[currentAnimation] <= currentFrame)
{
    currentFrame = 0;
}

while(!stream.eof()) が悪い理由については、Lokiの回答を参照してください

于 2013-10-30T13:16:24.913 に答える
0

いくつかの問題:

ここには 10 個のアイテムしかありません:

std::string param[10];

しかし、ここでは 10 のチェックはありません。

while(!stream.eof())

したがって、これにより 10 を超える数が追加される可能性があり、確実に問題が発生します。

また、この形式のループはほとんどの場合間違っています。

while(!stream.eof())
{
    getline(stream, param[n], '$');
    frames[n] = atoi(param[n].c_str());
    n++;
}

入力に不正なデータがある場合、これは無限ループに入ります。そうしないと、EOF に到達std::getline()すると、データの読み取りに失敗し、eof フラグが設定されますが、フレームに割り当てられます (そして n がインクリメントされます)。atoi()on bad data は 0 を返すため、最後の要素は 0 にFramesなります (これが意図した動作であるかどうかはわかりません (ただし、ずさんです)。

正しいスタイルは、読み取りを while 条件に入れることです。したがって、これら 2 つのことを一緒に追加すると、ループは次のようになります。

while(n < 10 && getline(stream, param[n], '$'))
{
    // loop is only entered if the read succeed.

    // Not sure about the type of `frames` so hard to talk about
    // if this loop is still correct. The meaning has changed slightly.
    frames[n] = atoi(param[n].c_str());
    n++;
}
if (n < 10) {/*We have an issue with not enough data!*/}
于 2013-10-30T13:35:18.577 に答える
0

書く

int n=0;
while(!stream.eof() && n < 10)
{

...

currentFrame++;
if(currentFrame < 10 && frames[currentAnimation] <= currentFrame)
{
    currentFrame = 0;
}

または次のようなものを使用します

currentFrame = (currentFrame + 1) % 10;
于 2013-10-30T13:12:42.813 に答える