读取文本文件以构建C++
Reading Text files to structure C++
我正在使用结构,但我不知道如何从文本文件添加信息。这是我的基本结构。我正在为我的结构添加年龄和名称。
using namespace std;
struct stud1
{
int age;
char name[20];
};
int main()
{
stud1 stud =
{
9,
"Lee"
};
cout<< stud.name <<endl;
}
在代码的末尾,Lee将被打印出来。我想添加信息,但来自文本文件。如何将文本文件的第一行添加到结构中?
这是文本文件:
10 John
12 Tim
11 Jack
首先,根据 SO 规则,您应该在提问时提供 MCVE。其次,您应该避免using namespace std;
因为它打开了全局命名空间污染的闸门。为了方便起见,您可以执行诸如using std::cout;
之类的操作,而无需打开整个标准命名空间。最后,如果你只是使用std::string
而不是char[]
在你的struct
生活会更容易,但无论如何,这是基本的想法。您可以直接从输入文件中读取年龄和名称到局部变量中,然后根据这些输入值设置结构元素。这是假设输入文件的每一行都像您所说的那样,并且没有错误检查。
#include <fstream> // for std::ifstream
#include <string> // for std::string
#include <cstring> // for strcpy()
std::ifstream infile("garbage.txt");
if (infile.is_open())
{
int age;
std::string namestr;
while (infile >> age >> namestr)
{
stud1 temp;
temp.age = age;
strcpy( temp.name, namestr.c_str() );
// do whatever before struct goes out of scope
}
infile.close();
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 无法在 CLion 中构建 C++ 项目
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何使用ndk-build.cmd构建Android.so文件
- libssh 的函数在构建 libssh 时无法在 Qt 和 cmake 错误中找到
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 无法使用Qt Creator在Windows中构建yaml-cpp
- 构建一个由C和C++文件组成的库
- llvm构建器向基本块添加终止符
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 如何跨平台将二进制资源构建到程序中?
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- 如何解决 Ninja c++ 构建和执行问题
- 使用 cmake 的 LLVM 构建在 tsan_libdispatch_mac.cc 期间失败; "Error: conflicting types for ..."
- CMake WxWidgets项目成功地在Linux上构建,但没有在Windows上构建
- 更改命令行 qt5 源代码构建配置的正确/快速方法
- 用CMake构建C++协议
- Mingw-64 在构建和安装后不会编译 openCV 代码