2015-04-30 20 views
-1

如果用戶輸入y,則該代碼應該重置High_Scores.txt文件,但無論輸入什麼內容,都會重置該代碼。任何幫助是極大的讚賞。即使條件不符合,文本文件也將被重置。 (C++)

// Reset 
// Include the libraries 
#include <iostream> 
#include <string> 
#include <fstream> 

//Use the standard namespace 
using namespace std; 

// Declare global variables 
char Ans; 


void main() 
{ 
    //Declare local variables 
    int High_Score[5]; 
    string High_Score_Name[5]; 
    int Rank; 

    // Initialize a high score at 0 
    High_Score[4] = 0; 

    // Input the high scores from a file 
    ifstream Input_High_Scores; 
    Input_High_Scores.open("High_Scores.txt"); 

    for (int i = 0; i < 5; i++) 
    { 
     Input_High_Scores >> High_Score[i]; 
     Input_High_Scores >> High_Score_Name[i]; 
    } 
    Input_High_Scores.close(); 

    if (High_Score[4] == 0) 
    { 

     //Initialize local variables 
     High_Score[0] = 25000; 
     High_Score[1] = 12000; 
     High_Score[2] = 7500; 
     High_Score[3] = 4000; 
     High_Score[4] = 2000; 
     High_Score_Name[0] = "Gwyneth"; 
     High_Score_Name[1] = "Adam"; 
     High_Score_Name[2] = "Nastasia"; 
     High_Score_Name[3] = "Nicolas"; 
     High_Score_Name[4] = "Dani"; 
    } 




    // Print the high score list 
    cout << "High Score List" << endl; 
    cout << endl; 
    for (int i = 0; i< 5; i++) 
    { 
     cout << High_Score[i] << " " << High_Score_Name[i] << endl; 
    } 

    // Output the high scores to a file 




    cout << "Would you like to reset the high scores list? (y or n)" << endl; 
    cin >> Ans; 

    if (Ans = 'y') 
    { 

     //Initialize local variables 
     High_Score[0] = 25000; 
     High_Score[1] = 12000; 
     High_Score[2] = 7500; 
     High_Score[3] = 4000; 
     High_Score[4] = 2000; 
     High_Score_Name[0] = "Gwyneth"; 
     High_Score_Name[1] = "Adam"; 
     High_Score_Name[2] = "Nastasia"; 
     High_Score_Name[3] = "Nicolas"; 
     High_Score_Name[4] = "Dani"; 
     // Output the high scores to a file 
     ofstream Output_High_Scores; 
     Output_High_Scores.open("High_Scores.txt"); 
    } 

    system("PAUSE"); 
} 
+10

使用''==而不是'=':'答==「y''。 – AlexD

+0

非常感謝,我記得改變了這個,試圖解決它,所以肯定還有其他一些錯誤。現在效果很好,再次感謝! – TRUTHjustice

+1

順便說一句,檢查編譯器警告。如果在條件運算符中使用賦值,它可能是一個。 – AlexD

回答

0

問題是與if (Ans = 'y'),使用if (Ans == 'y')。觀察==if的條件。當您使用=時,條件爲真(在這種情況下),無論您輸入什麼內容。

+0

在這種情況下爲true,但是'if(var = other_var)'具有用法 - 例如:'if(derived = dynamic_cast (base))'是單線。 – hauron

+0

@hauron yup。我錯過了這一點。相應地編輯它;) – Abhishek

0

在你的if語句分配值來答,不檢查等於if (Ans = 'y')
在評論正如已經指出。

0

小,但嚴重的錯誤,你正在聽。

if (Ans = 'y') 

在編寫代碼時,這應該是一個條件。但是你沒有檢查一個條件聽到。 Insted你分配'y'值喲Ans

注意,=是用來指定和==用來表示相等的。

所以,你應該改變你的if語句條件

if (Ans == 'y') 
相關問題