如何从C++中读取文件到int/浮点值的数据?
可能这个问题已经被问过了,我已经找到了类似的话题,但我仍然无法解决我的问题。 我有一个由IDL生成的数据文件,其中包含整数和浮点值。我想在C++中读取这个数据文件。 我到现在为止所做的:如何从C++中读取文件到int/浮点值的数据?,c++,char,int,ifstream,C++,Char,Int,Ifstream,可能这个问题已经被问过了,我已经找到了类似的话题,但我仍然无法解决我的问题。 我有一个由IDL生成的数据文件,其中包含整数和浮点值。我想在C++中读取这个数据文件。 我到现在为止所做的: fstream prjfile; prjfile.open("fileName", ios::in|ios::ate); if (prjfile.is_open() == false) { std::cout << "Cannot open project file\n"; } else {
fstream prjfile;
prjfile.open("fileName", ios::in|ios::ate);
if (prjfile.is_open() == false) {
std::cout << "Cannot open project file\n";
}
else {
std::vector <char> memPrj(0);
std::cout << "project size" << prjfile.tellg() << std::endl;
int sizePrj;
sizePrj = prjfile.tellg();
//store all values of the file in memPrj vector
memPrj.resize(sizePrj);
prjfile.seekg(0, std::ios::beg);
prjfile.read(&memPrj[0], sizePrj);
//now change the integer values to int
vector<int> mask;
//store the values in the mask vector
mask.push_back(memPrj[0] - '0' + 48);
mask.push_back(memPrj[1] - '0' + 48);
mask.push_back(memPrj[2] - '0' + 48);
}
而值应为:144257144
有人知道我的错误在哪里吗?
数据的其余元素是浮点值。如何将字符值转换为浮点值
提前谢谢 重复>>在循环中读取
#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
}
如果您确切知道一个文件中有多少个元素,则可以链接>>运算符:
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
你把生活搞得太复杂了。 以下是要点:
std::string text_line;
while (std::getline(prjFile, text_line))
{
int value;
std::istringstream text_line;
text_line >> value;
mask.push_back(value);
std::string comma;
std::getline(text_line, comma, ',');
text_line >> value;
mask.push_back(value);
std::getline(text_line, comma, ',');
text_line >> value;
mask.push_back(value);
}
由于遇到浮点数时,读取整数最多只能读取一个小数点,因此将跳过剩余字符,直到下一个逗号
编辑1:
另一种方法是以浮点形式读取值,然后在附加到向量之前将其转换为整数 是的,你是对的,已经有很多类似的问题了。搜索Internet上的StAcExpLoad C++读取文件逗号分隔。在这种情况下,我已经找到了类似的话题,但我仍然无法解决我的问题。是的,如果不知道你对这些问题的困惑,我们无法可靠地帮助你,而不只是重复现有的20000个答案,而不让你进一步理解。然后下一个家伙就到了20001年。请更清楚地说明您在现有指南中没有提及的内容。为什么要减去“0”再加上48?我相信48是ASCII值,0,为什么你使用PrimTf来输出C++?为什么使用Prtff C流和C++流FSt流?你应该坚持一种流样式。你的例子扩展得不太好。如果我知道一个文件中有1000个元素,我不会用一行来读取所有1000个元素。考虑一个循环和STD::向量。OP的数据文件也有逗号。您的解决方案不处理逗号。
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
std::string text_line;
while (std::getline(prjFile, text_line))
{
int value;
std::istringstream text_line;
text_line >> value;
mask.push_back(value);
std::string comma;
std::getline(text_line, comma, ',');
text_line >> value;
mask.push_back(value);
std::getline(text_line, comma, ',');
text_line >> value;
mask.push_back(value);
}