最近遇到的C++数字和字符串的转换问题
1、
用itoa 和atoi 在头文件#include<cstidlib>
itoa用法:
char * itoa ( int value, char * str, int base );
value Value to be converted to a string. str Array in memory where to store the resulting null-terminated string. base Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.
其中返回值和str是一样的。
atoi用法:
int atoi (const char * str);
/* atoi example */ #include <stdio.h> /* printf, fgets */ #include <stdlib.h> /* atoi */ int main () { int i; char buffer[256]; printf ("Enter a number: "); fgets (buffer, 256, stdin); i = atoi (buffer); printf ("The value entered is %d. Its double is %d.\n",i,i*2); return 0; }
2、sprintf 在头文件#include<cstdio>
int sprintf ( char * str, const char * format, ... );
Return value:
On success, the total number of characters written is returned. This count does not include the additional null-character automatically appended at the end of the string.
On failure, a negative number is returned.
/* sprintf example */ #include <stdio.h> int main () { char buffer [50]; int n, a=5, b=3; n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a string %d chars long\n",buffer,n); return 0; }
3、字符串流的使用
头文件:#include<sstream>
stringstream strm; 创建自由的stringstream对象
stringstream strm(s); 创建存储s的副本的stringstream对象,其中s是string类型的对象
strm.str(); 返回strm中存储打的string类型对象
strm.str(s); 将string类型的s复制给strm,返回void
string line,word; while(ginline(cin,line)) { istringstrem strem(line); while(strem >> word) { //do something } }
class istream 可用来读取数据
class ostream 可用来写出数据
#include <sstream> #include <iostream> using namespace std; int main () { int val1=255, val2=587; ostringstream format_message; format_message << "val1: " << val1 << endl << "val2: " << val2 << endl; istringstream input_istring(format_message.str()); cout << input_istring.str() << endl; cout << format_message.str() << endl; string dump; int val11,val22; input_istring >> dump >> val11 >> dump >> val22; cout << val11 << " " << val22 << endl; return 0; }