#Reading data from file.

4 messages · Page 1 of 1 (latest)

obtuse vortex
#

I'm using this function to save data to file: ```c++
void result::saveResult()
{
std::fstream fileName;

fileName.open("savedResults.txt", std::ios::out);

if (!fileName)
{
    std::cout << " Error while creating the file ";
}
else {

    fileName << "time: " << time << "\n";
    fileName << "userName: " << userName << "\n";
    fileName << "howManyStations: " << howManyStations << "\n";
    fileName << "howManyPeopleTransported: " << howManyPeopleTransported << "\n";

    fileName.close();
}

}How can I take this data back using regex? c++
void result::readResult()
{
std::fstream fileName;

string x;

fileName.open("savedResults.txt", std::ios::in);

if (!fileName)
{
    std::cout << "File doesn’t exist.";
}
else
{

    while (true)
    {
        fileName >> x;

        if (fileName.eof())
        {
            break;
        }
    }
}

fileName.close();

//float time = std::regex reg("!~");

std::regex reg("time ");

}```

smoky vault
#

It will be helpful to tell us which language you use.

lean harbor
#

I'm pretty sure it's C++

trail prawn
#

Wait, why do you specifically want regex???

If you are going to only have 1 instance of this data, then I would recommend:

fileOut << time << '\n' << userName << '\n' << howManyStations: << '\n' << howManyPeopleTransported '\n'; // '\n' is similar to std::endl

int time, howManyStations, howManyPeopleTransported;
string userName;
fileIn >> time >> userName >> howManyStations >> howManyPeopleTransported;

Else if you're NOT going to add properties e.g.: UUID, money:

using namespace std;

struct Player {
    int stations, people_transported; // I, personally, like snake_case in C++
    int time;
    string name;
};

vector<Player> players;

int main(){

    // void read(){ 
    ifstream file_in("results.txt");
    while(true){
        Player player;
        file_in >> player.time >> player.name >> player.stations >> player.people_transported;
        if(file_in.eof()) break;
        players.push_back(player);
    }

    for(Player &player : players){
        player.time ++;
    }

    // void write(){ 
    ofstream file_out("results.txt");
    for(Player &player : players){ // you don't need the '&' here, here the reason is the data isn't written to
        file_out 
            << player.time << ' '
            << player.name << ' '
            << player.stations << ' '
            << player.people_transported << std::endl;
    }
    file_out.close() // You should do this for every stream, I guess...
}

If you will be changing your data, I'd just recommend using yaml-cpp... Maybe a switch statement, e.g.
PSEUDOCODE:

while(true){
    Player player; string key; fileIn >> key; /* key.resize(key.size() - 1, ' '); // removes last character/colon */
    switch(key) { case "time:": fileIn >> player.time; break; ... }
    ...