#c #file #info
#c #файл #Информация
Вопрос:
Я хочу создать программу, которая вводит данные участников в текстовый файл с помощью функции ввода класса. Затем функция вывода используется для извлечения информации об одном участнике за раз путем ввода их идентификатора.
В этом моем коде цикл 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<<"nnEnd of Data Viewing.n";
}
Я хочу, чтобы сначала он прочитал только идентификатор, в первой строке его 1037. Если идентификатор совпадает, он должен отображать следующие 2 элемента в файле; имя и оценка.
Комментарии:
1. Это не решает вопрос, но приобретите привычку инициализировать объекты значимыми значениями, а не инициализировать их по умолчанию и немедленно записывать «правильные» значения. То есть измените
ofstream in; in.open("Participant.txt", ios::app);
наofstream in("Participant.txt', ios::app);
. И вам не нужно вызыватьin.close();
. Это сделает деструктор.
Ответ №1:
Проблема в том, что вы пытались использовать holderID (int) непосредственно из потока out. Попробуйте использовать string для чтения того же значения out и используйте stoi() для преобразования того же значения в int. Также обратите внимание, что при написании первым идет имя, за которым следует идентификатор и оценка.
Также используйте приведенное ниже в качестве ссылки. Я использовал std::map для хранения значения id, имени и оценки.
#include <string>
#include <fstream>
#include <map>
#include <iostream>
#include <algorithm>
#include <sstream>
class Participants
{
int id;
int score;
std::string name;
public:
Participants(): id(0), score(0)
{}
Participants(int id, int score, std::string name): id(id), score(score), name(name)
{}
~Participants()
{}
int GetId()
{
return id;
}
std::string encode()
{
auto strRet = std::string( name " " std::to_string(id) " " std::to_string(score) "n");
return strRet;
}
void decode(std::string text)
{
std::stringstream ss(text);
std::string buf;
//Read Name
std::getline( ss, buf , ' ');
name = buf;
//Read id
std::getline( ss, buf , ' ');
id = std::stoi( buf );
//Read Score
std::getline( ss, buf , 'n');
score = std::stoi( buf );
}
};
class DataReader
{
std::string fileName;
std::fstream myfile;
public:
DataReader(std::string fileName): fileName(fileName)
{
}
~DataReader()
{
}
void ReadParticipants(std::map<int, Participants> amp;MapParticipants)
{
myfile.open(fileName, std::ios::in);
MapParticipants.clear();
if ( myfile.is_open() )
{
std::string line;
while ( std::getline(myfile, line) )
{
Participants oParticipants;
//Decode and Add to map
oParticipants.decode(line);
//Add to map
MapParticipants[ oParticipants.GetId() ] = oParticipants;
}
}
myfile.close();
}
void WriteParticipants(std::map<int, Participants> amp;MapParticipants)
{
//Load Map to find Duplicates
std::map<int, Participants> MapParticipants_exist;
ReadParticipants(MapParticipants_exist);
myfile.open(fileName, std::ios::app);
if ( myfile.is_open() )
{
for ( auto oParticipants : MapParticipants)
{
//Check for Duplicates (to Write or not)
if ( MapParticipants_exist.find(oParticipants.first) == MapParticipants_exist.end() )
{
auto text = oParticipants.second.encode();
myfile << text.c_str();
}
}
}
myfile.close();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
DataReader oReader("File.txt");
std::map<int, Participants> MapParticipants;
//Make Some Participants
Participants p1(1, 50, "TOM");
Participants p2(2, 40, "TIM");
Participants p3(3, 80, "JERRY");
//Add them to map
MapParticipants[p1.GetId()] = p1;
MapParticipants[p2.GetId()] = p2;
MapParticipants[p3.GetId()] = p3;
oReader.WriteParticipants(MapParticipants);
oReader.ReadParticipants(MapParticipants);
//Find and Display
int id = 2;
auto it = MapParticipants.find(id);
if ( it != MapParticipants.end() )
{
//Show/Print
...
}
return 0;
}