简体   繁体   中英

How to access other comma separated values from a txt file. C++

ifstream f("events.txt");
if (f.is_open())
{
    string l,t;
    string myArray[5];
    int i = 0;
    while (getline(f, l))
    {
        getline(stringstream(l), t, ',');
        cout << t << endl;
        myArray[i] = t;
        cout << myArray[i] << endl;
        i = i + 1;
    }

So I have a file called 'events.txt' that contains:

An angry orc hits you with his weapon!,-50
A mage casts an evil spell on you!,-20
You found a health potion!,25
An enemy backstabs you from the shadows!,-40
You got eaten by a Dragon!,-1000

This part of the program so far prints out the sentence up to the comma and stores it into an array. My problem is I also want to access the number in some way and store it into another array or to use it when the event occurs, as it'll be used to lower player HP.

Thanks in advance!

A simple way to do this:

Define a struct to store your data:

struct Event {
    std::string message;
    int number;
}

(Don't store both items in separate arrays, they belong together.)

Create a vector of this struct and add the items to it:

std::vector<Event> events;
while (getline(f, l)) {
    size_t pos = l.find(',');
    Event e;
    e.message = l.substr(0, pos);
    e.number = std::stoi(l.substr(pos+1));
    events.push_back(e);  
}

However this assumes that the string has exactly one comma. If you want to be more flexible, use std::strtok or regular expressions.

Another recommendation: Separate I/O from parsing. Don't try to read data types like int directly from the input stream, as suggested in one of the comments. Instead, read the whole line or whatever your parsing unit is and then do the parsing. This makes your code more readable and simplifies error handling and debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM