将字符串分成三个独立的双打

Separating String Into three Separate Doubles

我有一串从文件中读取的行。字符串:("2021.2 12341.29 42.1")。我需要将三个数字中的每一个提取为每个 space 显示的每个值的双精度数,以暗示那里有一个新数字。这些数字不会总是具有相同的间距,因为我正在对多行进行此操作,所以我不能只通过间距中的相同精确点。这是我目前所拥有的。

string vert; //I already got the read line so here for example I am subing in a value for vert.
vert = "2021.2 12341.29 42.1";
double num1, num2, num3;

for (int i = 0; i < vert.length(); i++){

...
}

使用std::istringstream:

#include <sstream>
#include <string>
#include <iostream>

int main()
{
   std::string vert = "2021.2 12341.29 42.1";
   double num1, num2, num3;
   std::istringstream strm(vert);
   strm >> num1 >> num2 >> num3;
}

解决方案 std::stringstream presented by 就是您所需要的。

我要补充一点,如果您已经知道字符串中有多少个双精度值,它就可以很好地工作,但如果您不知道,您就不能真正那样使用它,您需要一个可变大小的容器可以容纳您的变量,例如 std::vector.

Online demo

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::string vert;
    vert = "2021.2 12341.29 42.1";

    std::vector<double> nums;   //vector of doubles
    double temp;                //temporary to hold the converted double
    
    std::stringstream ss(vert); //convert to stream
    while(ss >> temp){
        nums.push_back(temp);   //add numbers to the vector
    }
}