【发布时间】:2017-03-22 18:55:07
【问题描述】:
我的技能非常基础。我正在尝试为文本游戏制作保存和加载功能。这是我的代码:
#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=="\0")
{
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 复合词时,就会出现问题。例如,当我输入“名称名称”时,player_name 变成名称,player_class 变成名称,实际的 player_class 没有放入任何变量中。
我尝试了rdbuf() 功能,但是没有用,我什至还不明白。我用stream、string、c.str()试过了,我在网上找到的所有东西都能理解,但总是出错。
【问题讨论】:
标签: c++ string file int loading