c++ - 如何在 C++ 中将文本文件保存为带有字符串的结构
问题描述
我想将文件的内容保存到结构中。我尝试使用 seekg 和 read 对其进行写入,但它不起作用。
我的文件是这样的:
johnmayer24ericclapton32
我想将姓名、姓氏和年龄存储在这样的结构中
typedef struct test_struct{
string name;
string last_name;
int age;
} test_struct;
这是我的代码
int main(){
test_struct ts;
ifstream data_base;
data_base.open("test_file.txt");
data_base.seekg(0, ios_base::beg);
data_base.read(ts, sizeof(test_struct));
data_base.close();
return 0;
}
它不编译,因为它不希望我在 read 函数上使用 ts。是否有另一种方式 - 或方式 - 做到这一点?
解决方案
您必须开发一种特定的算法,因为“字段”之间没有分隔符。
static const std::string input_text = "johnmayer24ericclapton32";
static const std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
static const std::string decimal_digit = "0123456789";
std::string::size_type position = 0;
std::string artist_name;
position = input_text.find_first_not_of(alphabet);
if (position != std::string::npos)
{
artist_name = input_text.substr(0, position - 1);
}
else
{
cerr << "Artist name not found.";
return EXIT_FAILURE;
}
同样,您可以提取出数字,然后用于std::stoi
将数字字符串转换为内部表示数字。
编辑 1:拆分姓名
由于名字和姓氏之间没有分隔符,您可能需要一个可能的名字列表,并使用它来找出名字的结尾和姓氏的开头。
推荐阅读
- terraform - Terraform Apply 与 Terraform Plan 有不同的“计划”
- java - 无法在 android pie 中使用 INTENT_VIEW 它什么也没显示
- c++ - 如何在运行时切换 C++11 中的模板?
- java - 如何检查重复值转到数据库
- java - 如何在html中调用jar小程序文件
- arrays - 如何确保数组中的所有元素都是唯一的?
- html - 如何使 div 内容不会过度扩展
- javascript - 如何路由嵌入了查询字符串的搜索 URL?
- python - 如何在 Python 中按组执行 proc rank(SAS 函数)?
- php - 在 PHP 中按键和求和值对多维数组进行分组