sscanf、sprintf 也可以用,但是不建议使用,实际上 c++ 实现 string 和其他数据类型的转换很容易完成,见如下代码:
- #include <iostream>
- using std::cout;
- using std::endl;
- #include <string>
- using std::string;
- #include <sstream>
- using std::stringstream;
- using std::ostringstream;
- template <class T>
- string toString(const T& s);
- int main()
- {
- string value = "";
- int inum = 0;
- double dnum = 0.0;
- value = "123";
- stringstream strStream;
- strStream << value;
- strStream >> inum;
- strStream.clear(); // 必须 clear,否则下一次调用不成功
- value = "123.45";
- strStream << value;
- strStream >> dnum;
- cout << inum << " " << dnum <<endl;
- string test = "";
- test = toString(dnum);
- cout << test << endl;
- return 0;
- }
- //其它类型转化为string类型
- template <class T>
- string toString(const T& s) {
- ostringstream os;
- os << s;
- return os.str();
- }
注意:若文本中数据是科学计数型,例如文本是:1.44e-07 仍能正常转化.