#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//C++方法:将数值转换为 string
string convertToString(double x)
{
ostringstream o;
if (o << x)
return o.str();
return "conversion error";//if error
}
//C++方法:将 string 转换为数值
double convertFromString(const string &s)
{
istringstream i(s);
double x;
if (i >> x)
return x;
return 0.0;//if error
}
int main(int argc, char* argv[])
{
//将数值转换为 string 的第一种方法:C 方法
char b[10];
string a;
sprintf(b,"%d",1975);
a=b;
cout<<a<<endl;
//将数值转换为 string 的第二种方法:C++方法
string cc=convertToString(1976);
cout<<cc<<endl;
//将 string 转换为数值的方法:C++方法
string dd="2006";
int p=convertFromString(dd)+2;
cout<<p<<endl;
return 0;
}
PHPz2017-04-17 13:25:22
Stringstream is a string stream, similar to cout cin in iostream
istringstream is similar to cin, except that the source of its input data comes from the internal string buffer. You can set the value of this buffer and then output the value inside to the variable you need
istringstream iss(str_in_buffer);// 类比 cin cin可以看成是 istream cin(stdin)
iss >> someint; //类比 cin cin >> someint;
Ostringstream is similar to cout, but the data input to ostringstream will not be output to the standard output (stdout, such as the terminal), but will be stored in a string type buffer, and then you can use .str to extract the buffer. Value
The analogy is similar to cin and istringstream above
伊谢尔伦2017-04-17 13:25:22
It’s a bit cute. I suggest you frame the code in markdown format.
In addition, the meaning of these N strings of codes is clearly stated in the comments. If you don’t read it carefully, the person who wrote the comments will be sad!