首页 > 解决方案 > 如何在 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。是否有另一种方式 - 或方式 - 做到这一点?

标签: c++

解决方案


您必须开发一种特定的算法,因为“字段”之间没有分隔符。

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:拆分姓名
由于名字和姓氏之间没有分隔符,您可能需要一个可能的名字列表,并使用它来找出名字的结尾和姓氏的开头。


推荐阅读