如何从 txt 文件访问其他逗号分隔值。 C++

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;
    }

所以我有一个名为 'events.txt' 的文件,其中包含:

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

到目前为止,这部分程序打印出逗号之前的句子并将其存储到数组中。 我的问题是我还想以某种方式访问​​该数字并将其存储到另一个数组中或在事件发生时使用它,因为它将用于降低玩家 HP。

提前致谢!

一个简单的方法:

定义一个结构来存储您的数据:

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

(不要将两个项目存储在单独的数组中,它们属于一起。)

创建此结构的向量并向其添加项目:

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);  
}

然而,这假设字符串只有一个逗号。如果你想更灵活,使用std::strtok或正则表达式。

另一个建议:将 I/O 与解析分开。不要尝试直接从输入流中读取 int 之类的数据类型,如评论之一所建议的那样。相反,阅读整行或任何你的解析单元,然后进行解析。这使您的代码更具可读性并简化了错误处理和调试。