为什么我的字符串转换为 float-conversion 不能用 istringstream 得到所有小数?

Why does my string to float-conversion not get all decimals with istringstream?

我正在逐行读取以定界符分隔的文件,并通过定界符“|”拆分输入那是在文件中使用的。在阅读该行时,我需要将“1.9”或“2.38”之类的输入转换为浮点数,但我似乎无法使其工作。我得到的只是第一个数字,如“1”或“2”。

我的代码有什么问题?我的结构 person 看起来像这样:

struct person {
    string firstname;
    string lastname;
    string signature;
    float length;

    string getFullName() {
        return firstname + " " + lastname;
    }
};

我的方法:

vector<person> LoadFromFile(string filename) {
    string line;
    vector<person> listToAddTo;
    person newPerson;

    ifstream infile(filename);
    if (!infile) {
        cerr << "Error opening file." << endl;
        //Error
    }

    while (getline(infile, line)) {
        string field;
        vector<string> fields;
        istringstream iss_line(line);
        while (getline(iss_line, field, DELIM)) {
            fields.push_back(field);
        }

        newPerson.firstname = fields[0];
        newPerson.lastname = fields[1];
        newPerson.length = strtof((fields[2]).c_str(),0);
        newPerson.signature = fields[3];

        listToAddTo.push_back(newPerson);
   }
return listToAddTo;
}

和文本文件:

morre|bo|1.8|morbox1|
mo|her|1.8|moxher1|
mo|herm|1.9|moxher2|

我尝试通过将输入写入字符串来隔离问题,结果显示得很好。
所以问题似乎出在从字符串到浮点数的转换上:

newPerson.length = strtof((fields[2]).c_str(),0);

查看 cpp.reference 上关于 std::strtof 的文档,我们可以发现

... it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value...

其中 "a valid floating-point representation" 可以是

... nonempty sequence of decimal digits optionally containing decimal-point character (as determined by the current C locale) (defines significand)

显然,在 OP 的语言环境中,小数点字符不是 .,就像在他们试图读取的文件中一样,因此数字被误解了。

值得注意的是,从 C++11 开始,我们可以将 std::string 直接转换为数字,而使用 std::stof 代替。