最近看到真么一段代码,就重温了一下C++的输入输出流。代码如下:
#include <iostream> #include <string> #include <sstream> std::string convertToString(double x) { std::ostringstream o; if( o << x) { return o.str(); } return "conversion error"; } double convertToDouble(const std::string &str) { std::istringstream i(str); double x; if( i >> x) { return x; } return 0.0; } int main() { char b[10]; std::string a; sprintf(b, "%d", 1975); a = b; std::cout << a << std::endl; std::string cc = convertToString(1976); std::cout << cc << std::endl; std::string dd = "2016"; int p = convertToDouble(dd) + 2; std::cout << p << std::endl; return 0; }