2017-09-27 9 views
0

私のプログラムがクラッシュする理由を理解できないようです。 "//名前のオプションを表示する"のwhileループを削除すると、プログラムはうまく動作します。コードはGCCでコンパイルされ、警告は表示されません。それは私のコンパイラでしょうか?それはfstreamと関係がありますか?ヘルプをいただければ幸いです。このループはどのようにプログラムをクラッシュさせますか?

ああ。あなたの疑問を抱いているこのプログラムがdata.txtを読み込み、適切なデータをplayer関数のインスタンスにロードします。現時点では不完全な状態です。あなたのデバッガを使用して

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 
#define cls system("cls"); 

bool Pload = false; 

void menu(); 

struct player { 
    int Px, Py, life = 20; 
    string name = ""; 
}; 

main() { 
    menu(); 
} 

void menu() { 
    string cLine,names,input; 

    int x,i,lineNum = 0; 
    fstream data; 

    menu: 

    data.open("data.txt"); 
    //Gets list of all names in data.txt, Adds them to string names 
    while(data.good()) { 
     getline(data,cLine); 
    if(cLine[0] == '/') { 
     names += cLine; 
    } 
}   
names += '\n'; 

//Displays name options 
cls 
cout << "Welcome to W A L K.\n\nWhat is your name?\n"; 
while(names[i] != '\n') 
{ 
    cout << i; 
    if(names[i] == '/') {cout << endl;i++;} else {cout << names[i];i++;} 
} 
cout << endl; 
getline(cin,input); 

//checks if name exits and loads file data into player/world objects 
data.close(); 
data.open("data.txt"); 
while(data.good()) { 
    lineNum++; 
    getline(data,cLine); 
    if(cLine.erase(0,1) == input) { 
     cls cout << "Found Name" << endl; 
     getline(cin, input); 

     } 

    } 
//Restarts menu 
data.close(); 
goto menu; 
} 

data.txtを

/Sammy 
x:0 
y:0 
l:20 
\ 

/Mary 
x:7 
y:9 
l:20 
\ 


/Dill 
x:7 
y:9 
l:20 
\ 

/Jack 
x:7 
y:9 
l:20 
\ 

答えて

3

はこれを発見し、または単にいくつかのcoutステートメントを使用していただろう。

あなたは次のようにiを宣言する場合:

int x,i,lineNum = 0; 

あなたは3 intを宣言し、0lineNumを初期化します。他の2つはユニット化されたままなので、それらを使用するには未定義の動作です。

while(names[i] != '\n') // UB, i is unitialised 

がそうのように、1行に1つの変数を宣言して初期化することを好む:

auto x = 0; 
auto i = 0; 
auto lineNum = 0; 

autoの使用も値にそれらを初期化するためにあなたを強制します。

あなたは1行にすべてを書きたい場合は、

auto x = 0, i = 0, lineNum = 0; 

を書く必要があるだろう。しかし、それだけで読み取り可能ではないですし、誰もそれをお願い致しません。

+0

本当に助けてくれました。私は投票をするだろうが、これは私の最初の質問の一つです。ありがとうございました。 –

関連する問題