C++如何从文件中读取我想要的内容
C++ how to read what I want from a file?
例如,如何从结构化.txt文件中为C++代码中的变量赋值?如果我有以下input.txt的结构如下:
<Name> "John Washington"
<Age> "24"
<ID> "19702408447417"
<Alive Status> "Deceased"
在我的c++代码中,如果我有
ifstream read("input.txt",ios::in);
char name[64];
read>>name;//name will point to John Washington string
int age;
read>>age;// cout<<age will return 24;
int ID;
read>>ID;// cout<<ID will return 19702408447417
char Alivestatus[32];
read>>Alivestatus;//Alivestatus will point to Deceased string;
我怎样才能使它像上面那样工作?
As@πάῥεῖ在注释中提到,您将需要实现一个解析器,该解析器可以解释文件中的<>
标记。此外,我建议重新考虑数据类型。
具体来说,考虑到您使用char []
没有特殊原因,请切换到std::string
。我不知道你的代码的用例,但如果input.txt
碰巧包含的数据大于数组的大小,或者更糟的是,如果输入是用户控制的,这很容易导致缓冲区溢出和不必要的漏洞利用。std::string
还具有标准化、优化的优点,比char数组友好得多,并且具有各种有用的算法和功能,可随时使用。
关于文本文件解析,您也许可以实现以下内容:
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream input_file("input.txt");
std::string name_delimeter("<Name> ");
std::string age_delimeter("<Age> ");
std::string id_delimeter("<ID> ");
std::string alive_delimeter("<Alive Status> ");
std::string line;
std::getline(input_file,line);
std::string name(line,line.find(name_delimeter) + name_delimeter.size()); // string for the reasons described above
std::getline(input_file,line);
int age = std::atoi(line.substr(line.find(age_delimeter) + age_delimeter.size()).c_str());
std::getline(input_file,line);
std::string id(line,line.find(id_delimeter) + id_delimeter.size()); // the example ID overflows 32-bit integer
// maybe representing is a string is more appropriate
std::getline(input_file,line);
std::string alive_status(line,line.find(alive_delimeter) + alive_delimeter.size()); // string for the same reason as name
std::cout << "Name = " << name << std::endl << "Age = " << age << std::endl << "ID = " << id << std::endl << "Alive? " << alive_status << std::endl;
}
代码的基础只是读取文件的结构,并从中构造适当的数据类型。事实上,因为我在大多数数据类型中都使用了std::string,所以通过std::字符串的构造函数和可用函数可以很容易地构建正确的输出。
也许您是在循环中执行此操作,或者文件有几个结构。为了解决这个问题,您可以创建一个Record
类,该类重载operator >>
并根据需要读入数据。
相关文章:
- 如何设置一个范围来提取我想要获得的信息
- 链接列表运算符重载没有打印出我想要的内容
- 莱克斯没有返回我想要的东西
- 而不是那么多的 if 语句,我想要一个逻辑,我可以用一个语句或优化的方式来完成
- 我想要一个具有子函数的函数访问相同的命名函数,而不使用它取决于其子类的类
- 如何让m_refcount变量打印出我想要的值而不是垃圾
- 我想要一个改变数组快速排序的2个数字的函数
- 输出不是我想要C++的
- 使用运算符覆盖排序没有得到我想要的
- C ++,否则文本程序不会进入我想要的途径
- 如何声明一个未知大小的数组,然后输入直到我想要,然后获取数组的大小
- 我如何使用 juce 的文件过滤器描述我想要的文件过滤器?
- 如何设置此视觉工作室 (2015) 自定义生成步骤(工具?基本上,我想要一个修改头文件(c ++)的预处理器步骤
- 代码不会发送我想要的权衡
- 无法在openGL和GLUT中为我想要的确切对象设置动画
- 我如何强迫Visual Studio使用我想要的依赖性库名称
- 我的 OpenGL QQuickItem 没有我想要的大小
- 我可以/应该在 #ifndef 后输入任何我想要的东西
- C++ microshell,输入一个命令并使用fork(),dup(),pipe()将其通过管道传输到进程。只是我没有得到我想要的结果
- C++如何从文件中读取我想要的内容