gpt4 book ai didi

c++ - 使用分隔符一个空格和一个分号读取文件

转载 作者:太空宇宙 更新时间:2023-11-04 16:08:43 33 4
gpt4 key购买 nike

我写这个是为了解析一个带有数字的文件,其中分隔符只是一个空格。我的目标是读取文件的每个编号并将其存储在矩阵 A 的相应索引中。因此,读取的第一个数字应转到 A[0][0],第二个数字应转到 A[0][1],依此类推。

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() {
const int N = 5, M = 5;
double A[N*M];
string fname("test_problem.txt");
ifstream file(fname.c_str());
for (int r = 0; r < N; ++r) {
for (int c = 0; c < M; ++c) {
file >> *(A + N*c + r);
}
}

for (int r = 0; r < N; ++r) {
for (int c = 0; c < M; ++c) {
cout << *(A + N*c + r) << " ";
}
cout << "\n";
}
cout << endl;

return 0;
}

现在,我正在尝试像这样解析一个文件:

1 ;2 ;3 ;4 ;5
10 ;20 ;30 ;40 ;50
0.1 ;0.2 ;0.3 ;0.4 ;0.5
11 ;21 ;31 ;41 ;5
1 ;2 ;3 ;4 ;534

但它会打印(因此读取)垃圾。我该怎么办?


编辑

这是我在 C 中的尝试,但也失败了:

FILE* fp = fopen("test_problem.txt", "r");
double v = -1.0;
while (fscanf(fp, "%f ;", &v) == 1) {
std::cout << v << std::endl;
}

-1 将始终被打印。

最佳答案

您的 C 示例的问题:

warning: format ‘%f’ expects argument of type ‘float*’, but
argument 3 has type ‘double*’ [-Wformat=]

随时随地打开警告(-Wall -Wextra)并进行更多错误检查。

无论如何,要将 fscanf 转换为 double,您需要 %lf 而不是 %f

关于c++ - 使用分隔符一个空格和一个分号读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31292438/

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