Summarizing about:String to Int, int To string
经常在c++里面用到int 和string之间的互相转换问题,方法有很多,这里做一个汇总;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.
http://www.cplusplus.com/reference/iostream/ios/fail.html
http://www.cplusplus.com/reference/iostream/ios/clear.html
http://www.cplusplus.com/reference/iostream/istream/ignore.html
http://www.cplusplus.com/reference/iostream/streamsize.html
http://publib.boulder.ibm.com/infocenter/comphelp/v9v111/index.jsp?topic=/com.ibm.xlcpp9.aix.doc/standlib/header_limits.htm
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> |