gpt4 book ai didi

c++ - 以格式化/顺序方式从文本文件中提取数据

转载 作者:行者123 更新时间:2023-11-28 01:37:05 25 4
gpt4 key购买 nike

我有一个具有以下结构的 .txt 文件:

000010109000010309000010409

我需要这样阅读的地方:

00001 01 09
00001 03 09
00001 04 09

我有这样的结构:

struct A{
string number // first 5 numbers
int day; // 2 numbers
int month; // last 2 numbers
};

我试过这种方法。但是不要工作。

    char number[6];
char day[3];
char monthes[3];
ifstream read("file.txt");
for (int i = 0; i < 100; i++) {
read.get(number,6);
structure[i].number= number;
read.get(day,3);
structure[i].day= atoi(day);
read.get(month,3);
structure[i].month= atoi(month);
}

如何从文件中读取数据并将其存储到此结构中?如果数字在同一个月有很多天,如何比较。非常感谢。

最佳答案

你可以尝试这样的事情:

FILE *fp = fopen("file.txt", "r");
A a;
char x[6], y[3], z[3];
fscanf(fp, "%5s%2s%2s", x, y, z);
a.number = string(x);
a.day = atoi(y);
a.month = atoi(z);

编辑:

这是有效的 C++ 代码(使用 cstdiocstdlib),但是如果你想要一些 C++ 版本,你可以尝试这样的事情

// read from file.txt
std::ifstream inFile("file.txt", std::ios::in);
char number[6], day[3], month[3];
int cnt = 0;
while (inFile.get(number, 6) && inFile.get(day, 3) && inFile.get(month, 3)) {
// Let's assume that structure[] is array of struct A
structure[cnt].number = number;
structure[cnt].day = atoi(day);
structure[cnt].month = atoi(month);
++cnt;
}
// store to file2.txt
std::ofstream outFile("file2.txt", std::ios::out);
for (int i = 0; i < cnt; ++i) {
outFile << structure[i].number << ' ' << structure[i].day << ' ' << structure[i].month << std::endl;
// If you need fixed-width for day/month, use std::setw and std::setfill
}
// compare first two
if (cnt >= 2) {
if (structure[0].number == structure[1].number &&
structure[0].month == structure[1].month &&
structure[0].day == structure[1].day) {
std::cout << "Same!" << std::endl;
} else {
std::cout << "Different!" << std::endl;
}
}

关于c++ - 以格式化/顺序方式从文本文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833971/

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