[回复]
[修改] [删除]
[返回版面]
|
1 |
作者: admin, 讨论版: 编程世界, 发表时间: 2015-01-15 18:06:24 PST
标题: C++ conversion between number and string
关键字: C++
In C++,
Convert int to string:
#include <sstream>
string int2str(int n) {
stringstream o;
o << n;
return o.str();
}
Convert string to int:
#include <sstream>
int str2int(string s) {
int n;
istringstream iss(s);
iss >> n;
return n;
}
Conversion of string and double etc. is similar.
To convert from int or other types to string, you can also use function to_string().
Note: to remember which stringstream type to use, you can think this way:
- if return type is int, then use istringstream (starting with "i" or "int")
- if return type is string, then use string stream (string with "s" or "string")
See: http://www.cplusplus.com/reference/string/to_string/.
To use the to_string() function, include header: #include <string>.
In C++11, also in GCC4.5, compile with -std=c++0x flag.
------------
Another way of converting string to int:
int strToInt(string s) {
int d;
sscanf(s.c_str(), "%d", &d);
return d;
}
--
最后修改: admin on 2015-02-06 19:23:44 PST
※ 来源: homecox.com [来自: 128.]
|
|
|