Summarizing about:String to Int, int To string
点击次数:153 次 发布日期:2008-12-13 12:24:16 作者:源代码网
|
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(), " "); 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," ",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 assignedstring s;char b[MAX]; // max is the maximum no of digits in a numbersprintf(b,"%d",i);// C-style string formed without nulls+=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(缓冲区)中.返回值是写入的字符数量. 源代码网供稿. |
