-1
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!

Zone
  • 5
  • 2
  • Search for "C++ split string" – Mat Mar 19 '16 at 14:28
  • When you read each line you could just split the string and get the int. –  Mar 19 '16 at 14:30
  • 1
    See `std::getline` and `std::istringstream`. Use the latter to convert from the string to the integer. – Thomas Matthews Mar 19 '16 at 14:31
  • 1
    Note that in a valid csv format you can have the following line `"This event is in double quotes because it has comma here ->,. The string can have any number of commas ,,, as long as it is in double quotes",+100`. – Ivan Gritsenko Mar 19 '16 at 14:35

1 Answers1

0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Frank Puffer
  • 8,135
  • 2
  • 20
  • 45