在 c++ 中将字符串转换为双精度

Converting string to double in c++

本文关键字:转换 双精度 字符串 c++      更新时间:2023-10-16

我做了一个函数,它接收一行和一个分隔符,分隔线并返回浮点数向量(如java中的split函数)。这是函数:

vector<float> extractNumbers(string line, char delimiter) {
    vector<float> a;
    float f;
    string forNow = "";
    for (unsigned int i = 0; i < line.size(); i++) {
        if (line.at(i) == delimeter) {
            f = ::atof(forNow.c_str());
            cout << ::atof(forNow.c_str()) << endl;
            a.push_back(f);
            forNow = "";
        } else {
            forNow += line.at(i);
        }
    }
    f = ::atof(forNow.c_str());
    cout << f << endl;
    a.push_back(f);
    return a;
}

这是我正在尝试的文本文件:

3 3
1 1 1
1 2 1
1 1 1

我调用此函数:vector<float> floatLine = extractNumbers(line, ' ');当我尝试打印forNow参数时,我收到的数字就像文本中一样,但是当我打印f::atof(forNow.c_str())时,我收到 0 而不是第一行的前 3。有什么想法吗?

只是如果您不知道与文件交互的这种便捷方式。您可以像这样使用它们:

float a, b;
float c, d, e;
float f, g, h;
fstream file("data.dat", ios::in);
if (file) {
    file >> a >> b;
    file >> c >> d >> e;
    file >> f >> g >> h;
    file.close();
}