C++ 即使不满足条件,也要重置文本文件。(C+;+;)
如果用户输入了C++ 即使不满足条件,也要重置文本文件。(C+;+;),c++,C++,如果用户输入了y,则该代码应该重置High_Scores.txt文件,但无论输入什么,它都会重置该文件。非常感谢您的帮助 // Reset // Include the libraries #include <iostream> #include <string> #include <fstream> //Use the standard namespace using namespace std; // Declare global variables
y
,则该代码应该重置High_Scores.txt
文件,但无论输入什么,它都会重置该文件。非常感谢您的帮助
// 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");
}
//重置
//包括图书馆
#包括
#包括
#包括
//使用标准名称空间
使用名称空间std;
//声明全局变量
查尔安斯;
void main()
{
//声明局部变量
int高_分数[5];
字符串高分名称[5];
整数秩;
//将高分初始化为0
高分[4]=0;
//从文件中输入高分
ifstream Input_高分;
输入_High_Scores.open(“High_Scores.txt”);
对于(int i=0;i<5;i++)
{
输入高分>>高分[i];
输入高分>>高分名称[i];
}
输入高分。关闭();
如果(高分[4]==0)
{
//初始化局部变量
高分[0]=25000;
高分[1]=12000;
高分[2]=7500;
高分[3]=4000;
高分[4]=2000;
高分名称[0]=“Gwyneth”;
高分名称[1]=“亚当”;
高分名称[2]=“Nastasia”;
高分姓名[3]=“尼古拉斯”;
高分名称[4]=“Dani”;
}
//打印高分列表
问题在于if(Ans='y')
,使用if(Ans='y')
。在if
条件中观察=。使用=
时,条件为真(在本场景中),无论您的输入是什么。您在if语句中为Ans赋值,而不是检查是否等于:if(Ans='y')
,正如在注释中已经指出的那样。您确实犯了一个很小但很严重的错误
if (Ans = 'y')
在编写代码时,假设这是一个条件。但您不是在检查条件。而是在分配值yoAns
注意,=
用于赋值,=
用于表示相等
因此,您应该将if语句条件更改为
if (Ans == 'y')
使用=
而不是=
:Ans=='y'
。非常感谢,我记得我更改了它以尝试修复它,所以肯定还有其他一些错误。它现在工作得很好,再次感谢!顺便说一句,检查编译器警告。如果在条件运算符中使用赋值,则可能是一个。在本例中为true,但为'if'(var=other_-var)“有用法-例如:”(派生=动态_-cast(base))”是一行。