如何在C ++中从字符串获取所有十进制数字

-1 c++ string decimal

我正在尝试从c ++中的文本获取值(所有十进制数字)。但我有一个问题,我无法解决

#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;

}
Run Code Online (Sandbox Code Playgroud)

thefile.txt:

34.123456789 77.987654321
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,

a = 34.1235 
b = 77.9877
Run Code Online (Sandbox Code Playgroud)

但我想要

a = 34.123456789 
b = 77.987654321
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

编辑:我不想打印出a和b。我只希望他们得到确切的值。

Lig*_*ica 5

你不能

A float只能给您六个(ish)十进制有效数字。从字符串转换后,文件中的值不能保存在中float

首先,您需要切换到double,否则您甚至都不会获得带有完整数值的变量。

然后,对于输出,请小心指定所需的精度

请保持对浮点数的了解,并考虑使用字符串,具体取决于您对这些数据的处理方式。