C++读取包含多种变量的txt文件

C++ Reading a txt file containing multiple kinds of variables

我的技能很基础。我正在尝试为文字游戏制作保存和加载功能。这是我的代码:

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>

#include "variables.h"

// CORE FUNCTIONS
void save_game()
{
    std::ofstream file((savefile_path + "/" + player_name + ".txt").c_str());
    if (file.is_open())
    {
        file << engine_switch << std::endl;  //int
        file << map_switch << std::endl;     // int
        file << sub_map_switch << std::endl;  // int
        file << player_name << std::endl;  //string
        file << player_class << std::endl;  // string
        //file <<  << endl;
        file.close();
    }
    else
    {
        std::cout << "A PROBLEM OCCURED";
        system("pause");
    }
    return;
}

void load_game()
{
    system("cls");

    std::cout << "ENTER THE SAVE FILE NAME (SAME AS YOUR CHARACTER NAME)\nOR PRESS ENTER TO GO BACK TO MAIN MENU: ";
    fflush(stdin);
    getline(std::cin, player_name);
    std::string name=player_name;
    std::ifstream file((savefile_path + "/" + player_name + ".txt").c_str());
    if(file)
    {
        file >> engine_switch; // this is int
        file >> map_switch; // this is int
        file >> sub_map_switch;  /this is int
        file >> player_name;  //string
        file >> player_class; //string
        //file >> ;
        return;
    }
    else
    {
        if(player_name=="[=10=]")
        {
            engine_switch=1;
            return;
        }
        else
        {
            system("cls");

            std::cout << "COULDN'T OPEN THE SAVE FILE" << std::endl;
            system("pause");
            load_game();
        }
    }
    engine_switch=1;
    return;
}

当我输入由 space 分隔的多个单词组成的 player_name 复合词时,会出现问题。例如,当我输入 "name name" 时,player_name 变成名称,player_class 变成名称,实际的 player_class 没有放入任何变量。

我试过 rdbuf() 功能,但没有用,我什至还不明白。我用streamstringc.str()试了一下,网上找的都可以看懂,但总是出错。

您需要在 load-game 函数中使用 getline 而不是 >> 运算符。

而不是做 file >> player_namegetline(file, player_name) 这应该用于替换每次出现的 file >> someVar

编辑:我没有意识到其他的是整数值。对于那些您仍然应该使用 >> 运算符。

当您从流中提取字符串时,空格被视为分隔符。
更糟糕的是:在您的代码中, player_name 后面跟着 player_class 这也是一个字符串。你的程序应该如何解释这个:

10 15 20 John William Doe hero B 

您的程序如何猜测 John William Doe 是组合名称而 hero B 是类别?

最简单的解决方案是将所有字符串写在文件中的单独一行中。当你加载它时,你可以用 getline() 阅读它:

file >> engine_switch; // this is int
file >> map_switch; // this is int
file >> sub_map_switch;  /this is int
getline (file, player_name);  //string
getline (file, player_class; //string