c++中读取文件标识符信息放入结构体数组里
作者:野牛程序员:2023-07-04 18:24:34 C++阅读 2750
在C++中,你可以使用fstream
库来读取文件并将标识符信息存储在结构体数组中。下面是一个简单的示例代码:
#include <iostream> #include <fstream> #include <string> struct Identifier { std::string name; int id; }; int main() { const std::string filename = "identifiers.txt"; // 假设文件名为 identifiers.txt const int maxIdentifiers = 100; // 最大标识符数量 Identifier identifiers[maxIdentifiers]; // 结构体数组 std::ifstream file(filename); if (!file) { std::cerr << "无法打开文件 " << filename << std::endl; return 1; } std::string line; int count = 0; // 当前标识符数量 while (std::getline(file, line) && count < maxIdentifiers) { // 每行的格式为 "name id",使用空格分隔 std::string name; int id; std::istringstream iss(line); if (iss >> name >> id) { identifiers[count].name = name; identifiers[count].id = id; count++; } else { std::cerr << "无法解析行: " << line << std::endl; } } file.close(); // 打印读取的标识符信息 for (int i = 0; i < count; i++) { std::cout << "标识符 #" << i+1 << ": " << identifiers[i].name << " (ID: " << identifiers[i].id << ")" << std::endl; } return 0; }
在此示例中,假设文件中的每行都包含一个标识符的名称和ID,以空格分隔。你可以根据自己的需求进行调整。程序将逐行读取文件并将名称和ID存储在Identifier
结构体数组中,直到达到最大标识符数量或文件结束。然后,它将打印出存储在结构体数组中的标识符信息。
请确保在运行代码之前,创建一个名为identifiers.txt
的文件,并在其中添加标识符信息。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:什么是文件标识符?
- 下一篇:C++如何将字符串转化为字符数组