Summerizing out:string to int,int to string

C++整型转换技巧
转处百度NLP部门jiju[url]http://super-jiju.spaces.live.com/?_c11_BlogPart_BlogPart=blogview&_c=BlogPart&partqs=amonth%3d12%26ayear%3d2008[/url]

1.
integer = atoi( my_string.c_str() );


2.
#include <iostream>
#include <sstream>//用这个类;

int main()
{
using namespace std;

string s = "1234";
stringstream ss(s); // Could of course also have done ss("1234") directly.

int i;
ss >> i;
cout << i << endl;

return 0;
}


3
.#include <boost/lexcal_cast.hpp>

// ...
int i = 42;
std::string s = boost::lexical_cast<std::string>(i);
int j = boost::lexical_cast<int>(s)

4.
#include <iostream>
#include <limits>

using namespace std;

int main ( int argc, char* argv[] )
{
int i;
cout << "enter an interger (or some random garbage): ";
cout.flush();
while ( (cin >> i).fail() )
{
// clear the error flag in the cin object
cin.clear();
// discard the erroneous user input
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "ooops! please try again: ";
cout.flush();
}
cout << "thank you for entering " << i << endl;
}

This technique should be applicable to other stream objects and other non-integer types.


[url]http://www.cplusplus.com/reference/iostream/ios/fail.html[/url]
[url]http://www.cplusplus.com/reference/iostream/ios/clear.html[/url]
[url]http://www.cplusplus.com/reference/iostream/istream/ignore.html[/url]
[url]http://www.cplusplus.com/reference/iostream/streamsize.html[/url]
[url]http://publib.boulder.ibm.com/infocenter/comphelp/v9v111/index.jsp?topic=/com.ibm.xlcpp9.aix.doc/standlib/header_limits.htm[/url]
5.
string IntToString(int intValue) { 
char *myBuff;
string strRetVal;

// Create a new char array
myBuff = new char[100];

// Set it to empty
memset(myBuff,'\0',100);

// Convert to string
itoa(intValue,myBuff,10);

// Copy the buffer into the string object
strRetVal = myBuff;

// Delete the buffer
delete[] myBuff;

return(strRetVal);
}


6.最后一个偶认为最好

int i=4507;   // any value can be assigned
string s;
char b[MAX]; // max is the maximum no of digits in a number

sprintf(b,"%d",i);// C-style string formed without null

s+=b; //c++ string(c++ STL string) is not necessarily null terminated

标准 C I/O
sprintf
语法:
 #include <stdio.h>
int sprintf( char *buffer, const char *format, ... );

sprintf()函数和printf()类似, 只是把输出发送到buffer(缓冲区)中.返回值是写入的字符数量.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值