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==" ")
{
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()
功能,但没有工作,我什至还不明白它。我用stream
、string
、c.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
编辑:我没有意识到其他是整数值。对于那些,您仍应使用 >>
运算符。
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 写入超过 1GB 的.txt文件时出现奇怪的行为
- 视觉 如何循环访问C++中遵循类似格式的多个.txt文件?
- txt 文件中浮点数的最大和最小值
- 从.txt文件中读取浮点型数字并在公式中使用它们
- C++将文本从.txt文件解析为变量
- 在树结构.txt文件中搜索节点
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 在 txt 文件中显示前两个数字的程序
- 如何从具有两列的.txt文件创建并行数组?
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 如何读取 TXT 文件并仅将 int 存储在 C 中