2016-12-02 66 views
-1
string command; 
int ZaneNightTrain; 

NightTrain: 

cin.ignore(); 
getline(cin, command); 
transform(command.begin(), command.end(),command.begin(), ::toupper); 
if (command == "TALK TO ZANE") 
{ 

    if (ZaneNightTrain == 0) 
    { 
     cout << "\nZane: Blah Blah Blah 1\n\n"; 
     ZaneNightTrain++; 

     goto NightTrain; 
    } 
} 
else if (ZaneNightTrain == 1) 
{ 
    cout << "\nZane: Blah blah blah 2\n" << endl; 
    ZaneNightTrain++; 
    goto NightTrain; 
} 
else if (ZaneNightTrain == 2) 
{ 
    cout << "\nBlah blah blah 3\n" << endl; 

    ZaneNightTrain = 0; 

    goto NightTrain; 
} 

return 0; 
} 

我不知道爲什麼ZaneNightTrain = 0;自動結束程序。我可以將數字設置爲2,並且它可以完成它應該做的事情。我試圖設置它,所以他說的第一件事是1而不是0,它也開始結束程序。我有另一個版本的代碼,你輸入一個數字而不是一個字符串來說話,它沒有問題。程序在我設置整數值後很早結束

+2

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+0

這個問題目前無法猜測。建議:用一個有很好的可測試條件的循環替換那些'goto's,然後看看你的狀況。爲什麼要讓自己這麼努力? – user4581301

+0

如果'command' _isn't_「TALK TO ZANE」,如果'ZaneNightTrain'不是1或2,那麼函數結尾處的返回將被執行。 – 1201ProgramAlarm

回答

2

你沒有初始化的ZaneNightTrain

int ZaneNightTrain = 0; 

值這個前面的問題可以幫助你更全面地瞭解正在發生的事情。 Why do I see strange values when I print uninitialized variables?

TLDR是不能保證聲明變量的值,如果要檢查它作爲程序中的第一個操作,則必須將其設置爲默認值。

+0

我試過了,似乎沒有將它設置爲這個數字似乎還在上升。 – Dave

+0

您應該附加一個調試器,我們添加一些cout語句來查看變量的值,然後再進行比較。他們可能不是你所想的那樣。 – sclarson