我想制作一个通过类的输入功能在txt文件中输入参与者数据的程序。然后使用输出功能通过键入参与者的ID来一次提取单个参与者的信息。
在我的这段代码中,输入ID后,我的while循环将无限运行。我怀疑它找不到eof()。任何帮助将不胜感激。我是C ++的新手。
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
class Participant{
private:
int id, score;
string name;
public:
Participant(){
id = 0; score = 0; name = "";
}
void input(){
char choice;
ofstream in;
in.open("Participant.txt", ios::app);
do{
cout<<"Enter your ID: \t";
cin>>id;
cout<<"Enter your name: \t";
cin>>name;
cout<<"Enter your Score:\t";
cin>>score;
in<<name<<" ";
in<<id<<" ";
in<<score<<endl;
cout<<"Add another entry? (Y/N)\n";
cin>>choice;
}while(choice == 'y' || choice == 'Y');
in.close();
}
void output(){
int idout, holderID, holderS;
string holder, output;
cout<<"Enter the ID for more information related to the person:";
cin>>idout;
fstream out;
out.open("Participant.txt");
while(!out.eof()){
out>>holderID;
cout<<"looping...\n";
if(idout == holderID){
out>>holder;
cout<<"Name: \t"<<holder<<endl;
out>>holderS;
cout<<"Score:\t"<<holderS<<endl;
holder ="";
holderS=0;
break;
}
else continue;
}
out.close();
}
void max(){
}
};
int main(){
char choice;
Participant player;
cout<<"Asking for Input: \n";
player.input();
system("pause");
system("cls");
cout<<"Data Viewing: \n";
do{
player.output();
cout<<"\nDo you wish to extract information on other players?\n";
cout<<"Y - Yes."<<endl;
cout<<"N - No."<<endl;
cout<<"Choice: ";
cin>>choice;
}while (choice == 'y' || choice == 'Y');
cout<<"\n\nEnd of Data Viewing.\n";
}
我希望它首先只读取ID,在第一行中读取ID1037。如果ID匹配,它将显示文件中的下2个成员;名称和分数。
答案 0 :(得分:0)
问题是您尝试直接从输出流中使用holderID(int)。尝试使用字符串读取相同的out值,然后使用stoi()将其转换为int。 另外请注意,在编写第一个名称时,先是名称,然后是ID和分数。
也可以使用以下内容作为参考。我用std::map来存储ID,名称和分数的值。
<ListView x:Name="visitList" SeparatorColor="Black"
SeparatorVisibility="Default" BackgroundColor="White">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame Padding="2">
<Grid>
<Label Text="{Binding Time}" Grid.Column="0"/>
<Label Text="{Binding CustomerName}" Grid.Column="1"/>
<Label Text="{Binding status}" Grid.Column="2"/>
</Grid>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>