最近在处理字符串转数字时,控制台输出的转换结果总是出现自动四舍五入的情况;期间尝试了各种转换函数但转换结果仍然是经过四舍五入的;实际上并不是使用的函数问题,而是控制台显示的问题,实际转换结果是正确的,如果仅是使用转换结果,直接用即可!!!
1、输入数据
2、输出结果
3、代码实现
由于我读取的是 .tfw 中的数据,所以在代码实现上先对数据进行读取,然后做字符串转浮点型数据;
#include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <vector> #include <stdio.h> #include <cmath> #include <opencv2\opencv.hpp> #include <opencv2\imgproc\imgproc.hpp> #include <opencv2\core\core.hpp> #include <opencv2\highgui\highgui.hpp> #include "opencv2\imgproc\types_c.h" using namespace std; using namespace cv; int main() { ifstream ifs; //创建流对象 ifs.open(".\\wgs.tfw", ios::in); //打开文件 if (!ifs.is_open()) //判断文件是否打开 { cout << "打开文件失败!!!"; return 0; } //读取正确匹配特征点 vector<string> item; //用于存放文件中的一行数据 string temp; //把文件中的一行数据作为字符串放入容器中 while (getline(ifs, temp)) //利用getline()读取每一行,并放入到 item 中 { item.push_back(temp); } vector<double> res; //字符串转浮点型数据,使用 atof() 函数即可 for (int i = 0; i < item.size(); i++) { //数据类型转换,将string类型转换成float,如果字符串不是有数字组成,q则字符被转化为 0 res.emplace_back(atof(item[i].c_str())); } for (double num : res) cout << num << endl; system("pause"); return 0; }
4、字符串转浮点型数据实际结果
跑完代码后通过观察内存中的变量可知:字符串转浮点型数据小数点后的所有数据都是被保留的!!!