简体   繁体   English

在C ++中将字符串转换为double

[英]Converting string to double in c++

I've made a function that receives a line and a delimiter, separates the line and returns a vector of floats (like the split function in java). 我已经制作了一个函数,该函数接收一行和一个定界符,分隔行并返回一个浮点数向量(类似于java中的split函数)。 This is the function: 这是功能:

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

This is the text file I'm trying it with: 这是我正在尝试的文本文件:

3 3
1 1 1
1 2 1
1 1 1

I call this function: vector<float> floatLine = extractNumbers(line, ' '); 我称这个函数为: vector<float> floatLine = extractNumbers(line, ' '); When I try to print forNow parameter I receive the numbers just like in the text, but when I print f or ::atof(forNow.c_str()) I receive a 0 instead of the first 3 in the first line. 当我尝试打印forNow参数时,我收到的数字就像在文本中一样,但是当我打印f::atof(forNow.c_str())我收到的是0,而不是第一行的前3。 Any thoughts? 有什么想法吗?

Just if you don't know about such convenient way of interaction with files. 就算您不知道与文件交互的便捷方式。 You can use them like this: 您可以像这样使用它们:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM