[英]how to get all decimal number from string in c++
I'm trying to get value (all decimal number) from a text in c++. 我正在尝试从c ++中的文本获取值(所有十进制数字)。 But I have a problem and I couldn't solve it 但我有一个问题,我无法解决
#include "pch.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("C:\\thefile.txt");
float a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
thefile.txt: thefile.txt:
34.123456789 77.987654321
When I run the above code, 当我运行上面的代码时,
a = 34.1235
b = 77.9877
but I want 但我想要
a = 34.123456789
b = 77.987654321
what should I do? 我该怎么办?
EDIT: I don't want to print out of a and b. 编辑:我不想打印出a和b。 I just want they get the exact values.net 我只希望他们得到确切的值。
You can't. 你不能
A float
can only give you six (ish) decimal significant figures . float
只能给您六个(ish)十进制有效数字 。 The values in your file, after conversion from string, cannot be held in a float
. 从字符串转换后,文件中的值不能保存在float
。
First, you need to switch to double
, otherwise you won't even have a variable with the full numerical value. 首先,您需要切换为double
,否则您甚至都不会获得带有完整数值的变量。
Then, for output, be careful to specify the precision you want . 然后,对于输出,请小心指定所需的精度 。
Please remain aware of the foibles of floating-point, and consider sticking with strings, depending on what you're doing with this data. 请保持对浮点数的了解,并考虑使用字符串,具体取决于您对这些数据的处理方式。
There are two main things i see in your code. 我在您的代码中看到了两件事。
This code will work for you. 该代码将为您服务。
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("newfile.txt");
double a, b;
std::cout.precision(11);
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
you should read your inputs into a string and then convert them into double (depending on enough precision in float on your computer). 您应该将输入读取为字符串,然后将其转换为双精度(取决于计算机浮点数的精度)。 you can directly display strings. 您可以直接显示字符串。 A possible answer is here . 一个可能的答案在这里 。
string word;
openfile >> word;
double lol = atof(word.c_str());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.