gpt4 book ai didi

c++按元素编辑txt文件

转载 作者:行者123 更新时间:2023-11-30 03:55:06 26 4
gpt4 key购买 nike

我有一个 txt 文件,其中保存按以下顺序排列的信息:

Name somename
Age someAge
Address someAddress
...

我按如下元素查找此信息:

if (myfile.is_open())
{
while (myfile >> element1)
{
myfile >> element2;

if (element1 == "Name")
_name = element2; //element2 is someName in .txt file

if (element1 == "Age")
_age = element2; //element2 is someAge in .txt file
...
}
myfile.close();
}

等等...

也可以使用 ofstream 以这种方式编辑 txt 文件吗?

最佳答案

"It is possible to edit the txt file this way too using ofstream?"

是的,这是可能的。只是不是立即操纵文件内容(正如您可能正在考虑的那样)。

  1. 您使用 std::ifstream 读入文件一行一行变成std::vector<std::string>变量
  2. 您使用各种 std::string 操作这些行根据需要发挥作用
  3. 您打开与 std::ofstream 相同的文件(使用std::iosbase::trunc标志打开)
  4. 你写下你所有的std::vector<std::string>输出文件的变量

作为@Jerry Coffin mentioned ,您可以考虑首先创建被操作文件的备份。如果这样做,您还可以利用操作单个记录,而无需读入整个文件(如果它真的很大,可能会导致内存问题)。

关于c++按元素编辑txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com