使用getline解析和存储变量 我正在C++编写一个简单的沙箱文本游戏,刚刚开始保存文件。在查看了本网站和其他网站上的一些问题后,我选择了自己的问题,而不是使用boost库等

使用getline解析和存储变量 我正在C++编写一个简单的沙箱文本游戏,刚刚开始保存文件。在查看了本网站和其他网站上的一些问题后,我选择了自己的问题,而不是使用boost库等,c++,parsing,while-loop,savestate,C++,Parsing,While Loop,Savestate,我的保存代码工作正常,但是,我的加载代码没有按我所希望的那样工作 int loadGame(string filename){ string delim=":"; string readline; ifstream filestream; filestream.open(filename.c_str()); while(getline(filestream,readline)){ cout << readline << endl; stringstre

我的保存代码工作正常,但是,我的加载代码没有按我所希望的那样工作

int loadGame(string filename){
string delim=":";
string readline;

ifstream filestream;
filestream.open(filename.c_str());

while(getline(filestream,readline)){
    cout << readline << endl;
    stringstream linestream(readline);
string         data;
getline(linestream, data, ':');
linestream >> playername >> location[0] >> location[1] >> hitpoints >> coins >> axes >> swords >> food >> maps;
}
return 0;
}
在我看来,这似乎是非常冗长和低效的

示例保存可能如下所示:

playername:John
location[0]:400
location[1]:840
hitpoints:100
coins:35
axes:0
swords:0
food:0
maps:3
我知道这可能是措词不当,但我非常感谢在这个问题上的任何帮助。提前谢谢。
ps关于这里发布的代码的任何其他提示都很好:)

在loadGame函数中,您正在将未知的“arg”检查为字符串“null”,而不是null
playername John Doe
hitpoints 300
请注意,我使用了一个空格来分隔值和键。现在,您可以简单地执行以下操作:

std::string key, value;
while (<more input>)
{
    input_file >> key;
    std::getline(input_file, value);

    if (key == "playername")
        // whatever...
    else if (key == "maps")
        // stuff...
}
std::字符串键,值;
而()
{
输入\u文件>>键;
std::getline(输入文件,值);
如果(键==“播放名称”)
//不管怎样。。。
else if(键==“映射”)
//东西。。。
}

我已经删除了您提到的不相关代码,变量“arg”来自单独的函数。此外,null是该变量的一个潜在输入,因此不像看上去那么不正确!在这种情况下,结帐如下一:非常感谢。我刚刚玩过它,它现在似乎起作用了。谢谢你把我从解析的魔爪中解救出来
std::string key, value;
while (<more input>)
{
    input_file >> key;
    std::getline(input_file, value);

    if (key == "playername")
        // whatever...
    else if (key == "maps")
        // stuff...
}