即使条件不满足,文本文件也会被重置。 (C ++)

时间:2015-04-30 08:07:03

标签: c++

如果用户输入High_Scores.txt,则此代码应重置y文件,但无论输入什么,它都会重置它。任何帮助是极大的赞赏。

// 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");
}

3 个答案:

答案 0 :(得分:0)

问题在于if (Ans = 'y'),请使用if (Ans == 'y')。在if条件下观察 == 。当您使用=时,条件为真(在此方案中),无论您输入什么。

答案 1 :(得分:0)

您在if语句中为Ans分配值,而不是检查相等if (Ans = 'y')如前所述在评论中。

答案 2 :(得分:0)

你正在听的很小但很严重的错误。

if (Ans = 'y')

在编写代码时,这应该是一个条件。但是你没有检查听到的情况。您已将'y'值分配给Ans

请注意,=用于分配,==用于表示相等。

因此,您应该将if语句条件更改为

if (Ans == 'y')