2017-09-27 72 views
0

我似乎無法弄清楚爲什麼我的程序崩潰。當我在「//顯示名稱選項」下刪除while循環時,程序運行良好。代碼在GCC上編譯時沒有警告。它可以是我的編譯器嗎?它與fstream有什麼關係?幫助將不勝感激。這個循環是如何使我的程序崩潰的?

哦,是的。如果你想知道這個程序會讀取data.txt並將適當的數據加載到播放器功能的實例中。目前它處於不完整的狀態。

#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並初始化lineNum0;然而其他兩個仍然是單元化的,因此使用它們是未定義的行爲。

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

寧可聲明和初始化每行一個變量,像這樣:

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

採用auto也迫使你將它們初始化爲一個值。

如果你想它寫在一行,你必須寫

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

但它只是沒有可讀的,沒有人會感謝你的。

+0

哇,真的有幫助。我會投票,但這是我的第一個問題之一。謝謝。 –