gpt4 book ai didi

c++ - 用 C++ 读取文本文件

转载 作者:行者123 更新时间:2023-11-30 18:19:19 25 4
gpt4 key购买 nike

我正在 Ubuntu 上的 OpenCV 上工作。我正在尝试读取包含数字的文本文件,但我不断收到垃圾值,并且每次函数循环时都会重复相同的值。这是该部分代码:

FILE* fid = fopen("/trial","r");
while (fgetc(fid) != EOF)
{
fscanf(fid, "%f", &trainsample);
cout << trainsample << endl;
cvSetReal2D(traindata, i, j, trainsample);
j = j + 1;
if (j == 6)
i = i + 1;
}

最佳答案

为什么不使用 C++ ifstream 来完成此任务?

#include <iostream>
#include <fstream>

int main(){
std::ifstream fileStream("/trail");
double trainsample;
if(!fileStream.good()){
std::cerr << "Could not open file." << std::endl;
return 1;
}
while(fileStream >> trainsample){
std::cout << trainsample << std::endl;
}
if(fileStream.fail())
std::cerr << "Input file stream error bit is set, possible read error on file." << std::endl;
}

如果您更喜欢 C 文件处理,请尝试

#include <cstdio>

int main(){
FILE *fid = fopen("/trail","r");
double trainsample;
if(fid){
while(!feof(fid)){
fscanf(fid,"%lf",&trainsample); // Please notice "lf" when using double. Using "f" will result garbage.
printf("%lf\n",trainsample);
}
}
}

另请参阅cstdioifstream .

关于c++ - 用 C++ 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8795663/

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