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

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

本文关键字:txt 文件 变量 读取 包含多 C++      更新时间:2023-10-16

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

#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=="")
        {
            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;
}

当我输入用空格分隔的多个单词的player_name复合体时,就会出现问题。例如,当我输入"name name"时,player_name变成name,player_class变成name,实际player_class没有放入任何变量中。

我尝试了rdbuf()功能,但没有工作,我什至还不明白它。我用streamstringc.str(),我在网上找到的所有东西都试过了,但总是出错。

从流中提取字符串时,空格被视为分隔符。
更糟糕的是:在你的代码中,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
您需要

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

与其做file >> player_name不如做getline(file, player_name)这应该用于替换每次出现的file >> someVar

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