在c ++错误中读取空格分隔值文件 [英] Reading space separated values file in c++ error
问题描述
我试图从文件中获取浮点值,以便在我的程序中使用它们。我使用以下论坛构建程序 C ++:逐行读取文件 。
但是通过这样做获得的值似乎在结束时被截断。
我的代码
#include< iostream>
#include< cstring>
#include< sstream>
#include< fstream>
using namespace std;
int main()
{
ifstream文件;
file.open(test_file.ssv);
string line;
while(file.good()&&(getline(file,line)))
{
istringstream iss(line);
double a,b,c;
iss>> a>> b> c;
cout<< a<<< endl;
}
file.close();
return(0);
}
我获得的输出是
<$ c $ p>
9292.31
32432.2
我的文件有以下数据
9292.3123 4234.66 342.25423
32432.2423 3423.656 341.67841
有任何改进的建议吗?
解决方案您的标准流可能具有低浮点精度,因此只有在输出
float
时,才会看到一些小数位。std :: cout
。使用std :: ios_base :: precision
可提高精度,并使用std :: ios :: floatfield
输出固定或科学精度,例如:// modify precision
#include< iostream> // std :: cout,std :: ios
int main(){
double f = 3.14159;
std :: cout.unsetf(std :: ios :: floatfield); // floatfield not set
std :: cout.precision(5);
std :: cout<< f<< '\\\
';
std :: cout.precision(10);
std :: cout<< f<< '\\\
';
std :: cout.setf(std :: ios :: fixed,std :: ios :: floatfield); // floatfield set to fixed
std :: cout<< f<< '\\\
';
return 0;
}
输出:
< >
3.1416
3.14159
3.1415900000
I am trying to get float values out of a file to use them in my program. I used the following forum to construct the program C++: Read file line by line.
But the values obtained by doing so appear to be truncated at the end.My code
#include <iostream> #include <cstring> #include <sstream> #include <fstream> using namespace std; int main() { ifstream file; file.open("test_file.ssv"); string line; while(file.good() && (getline(file, line))) { istringstream iss(line); double a, b, c; iss >> a >> b >>c ; cout << a <<endl; } file.close(); return (0); }
The output that I obtain is
9292.31 32432.2
While my file has the following data
9292.3123 4234.66 342.25423 32432.2423 3423.656 341.67841
Any suggestions to improve upon this?
解决方案Your standard stream may have a low floating point precision and you therefore only see a few of the decimals when outputing a
float
withstd::cout
. Usestd::ios_base::precision
to increase the precision and look into usingstd:: ios::floatfield
to output fixed or scientific precision , example:// modify precision #include <iostream> // std::cout, std::ios int main () { double f = 3.14159; std::cout.unsetf ( std::ios::floatfield ); // floatfield not set std::cout.precision(5); std::cout << f << '\n'; std::cout.precision(10); std::cout << f << '\n'; std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed std::cout << f << '\n'; return 0; }
Outputs:
3.1416 3.14159 3.1415900000
这篇关于在c ++错误中读取空格分隔值文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!