字符如何隐式的转换为数字:一个字符型的数字减去‘0’后就会隐式地转换为数字,一个数字加上‘0’后就会隐式地转换为字符。
intnum='9'-'0';
chara=9+'0';
int inta=9+'0';
cout<<"num:"<<num<<endl;
cout<<"a:"<<a<<endl;
cout<<"inta:"<<inta<<endl;
1.1 使用stringstream
number to string
1 | int Number = 123;//number to convert int a string string Result;//string which will contain the result
stringstream convert; // stringstream used for the conversion
convert << Number;//add the value of Number to the characters in the stream
Result = convert.str();//set Result to the content of the stream
//Result now is equal to "123" |
string to number
1 | string Text = "456";//string containing the number int Result;//number which will contain the result
stringstream convert(Text); // stringstream used for the conversion initialized with the contents of Text
if ( !(convert >> Result) )//give the value to Result using the characters in the string Result = 0;//if that fails set Result to 0 //Result now equal to 456 |
Simple functionsto do these conversions
1 | template <typename T> string NumberToString ( T Number ) { stringstream ss; ss << Number; return ss.str(); } |
1 | template <typename T> T StringToNumber ( const string &Text )//Text not by const reference so that the function can be used with a { //character array as argument stringstream ss(Text); T result; return ss >> result ? result : 0; } |
缺点:
1) 内存风险
#include<cstdlib>
#include<iostream>
#include<sstream>
usingnamespace std;
intmain(int argc, char *argv[])
{
std::stringstream stream;
string str;
while(1)
{
//clear(),这个名字让很多人想当然地认为它会清除流的内容。
//实际上,它并不清空任何内容,它只是重置了流的状态标志而已!
stream.clear();
// 去掉下面这行注释,清空stringstream的缓冲,每次循环内存消耗将不再增加!
//stream.str("");
stream<<"sdfsdfdsfsadfsdafsdfsdgsdgsdgsadgdsgsdagasdgsdagsadgsdgsgdsagsadgs";
stream>>str;
// 去掉下面两行注释,看看每次循环,你的内存消耗增加了多少!
//cout<<"Size of stream= "<<stream.str().length()<<endl;
//system("PAUSE");
}
system("PAUSE");(不应该使用,可以用其他语句代替,如cin.get())。
return EXIT_SUCCESS;
} 把stream.str(""); 那一行的注释去掉,再运行程序,内存就正常了
看来stringstream似乎不打算主动释放内存(或许是为了提高效率),但如果你要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str("") )。
另外不要企图用stream.str().resize(0),或stream.str().clear() 来清除缓冲,使用它们似乎可以让stringstream的内存消耗不要增长得那么快,但仍然不能达到清除stringstream缓冲的效果(不信做个实验就知道了,内存的消耗还在缓慢的增长!),至于stream.flush(),则根本就起不到任何作用。
1.2 自定义字符串转数字
long atoi(const char *str)
{
long num = 0;
int neg = 0;
while (isspace(*str)) str++;
if (*str == '-')
{
neg=1;
str++;
}
while (isdigit(*str))
{
num = 10*num + (*str - '0');
str++;
}
if (neg)
num = -num;
return num;
}