kla*_*ack 3 c++ floating-point data-conversion c++11
我正在逐行读取分隔符分隔的文件,并通过分隔符'|'拆分输入 在文件中使用的那些.在读取行时,我需要将"1.9"或"2.38"之类的输入转换为浮点数,但我似乎无法使其工作.我得到的是第一个数字,如"1"或"2".
我的代码出了什么问题?我的Struct person看起来像这样:
struct person {
string firstname;
string lastname;
string signature;
float length;
string getFullName() {
return firstname + " " + lastname;
}
};
Run Code Online (Sandbox Code Playgroud)
我的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
和文本文件:
morre|bo|1.8|morbox1|
mo|her|1.8|moxher1|
mo|herm|1.9|moxher2|
Run Code Online (Sandbox Code Playgroud)
我尝试通过将输入写入字符串来隔离问题,这显示结果很好.
所以问题似乎是从字符串到float的转换:
newPerson.length = strtof((fields[2]).c_str(),0);
Run Code Online (Sandbox Code Playgroud)
查看有关std::strtofcpp.reference 的文档,我们可以找到它
...它需要尽可能多的字符来形成有效的浮点表示并将它们转换为浮点值...
"有效的浮点表示"可以是a
...非空的十进制数字序列,可选地包含小数点字符(由当前C语言环境确定)(定义有效数字)
显然,在OP的语言环境中,小数点字符不是a .,就像他们试图读取的文件一样,因此数字被误解了.
值得注意的是,从C++ 11开始,我们可以std::string直接将a 转换为数字std::stof.
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |