String digital conversion (C ++)

A, with streanstream (c ++) of

数据多的时候可能有点慢,不过很好用

1、 string—>数字(int、float、double)

	string str = "123";
	int num;
	stringstream ss;
    ss << str;
	ss >> num;
	cout << num << endl;

2, digital -> string

	int num = 32.123;
	string str;
	stringstream ss;
    ss << num;
	ss >> str;		//cout << ss.str() endl;一样的效果
	cout << str;

Second, using sprintf () and sscanf () (c language)

1, char type string -> Digital

	char str[]="123456";
	int num;
	sscanf(str,"%d",&num);//这里切换类型即可
	cout << num << endl;

2, the digital -> char string type

	char str[10];
	int num = 123465;
	sprintf(str,"%d",num);	//想改变其他的只需改变这的类型
	cout << str;

  Note: when in use here can be directly converted hexadecimal

Such as:

	//实例1
	char str[]="171";
	int num;
	sscanf(str,"%x",&num);
	cout << num << endl;//转为了16进制
	//实例2
	char str[]="AB";
	int num;
	sscanf(str,"%x",&num);//16进制转为10进制,171
	cout << num << endl;

Third, with itoa and atoi (c language)

1.char type string -> Digital

  • atof (): Converts a string to a double precision floating point value.
  • atoi (): to convert the string to an integer value.
  • atol (): to convert the string to a long integer.
  • strtod (): Converts a string to a double precision floating point value, and report all of the remaining numbers are not converted.
  • strtol (): the value into a long string, and to report all of the remaining digits can not be converted.
  • strtoul (): converts a string to an unsigned long integer value, and report all of the remaining numbers are not converted.
Example:
	char str[]="171";
	int num = atoi(str);
	cout << num << endl;

2, the digital -> char string type

  • itoa (): the integer value into a string.
  • ltoa (): The long integer value to a string.
  • ultoa (): unsigned long integer value to a string.
  • gcvt (): converting the floating-point number to a string, to take rounded.
  • ecvt (): double precision floating point value is converted to a string, the conversion results do not contain a decimal point.
  • fcvt (): Specifies the number of digits for the conversion accuracy, and the rest with ecvt ().
Example:

函数原型:char *itoa(int value, char *string, int radix);
input value is an integer, string string from the conversion, radix binary output is to several

	int num = 23;
	char str[10];
	itoa(num,str,10);
	cout << str;

Fourth, the transition between the string c ++ and c char *

1.char—>string

	char p[20] = "Hello World!";
   		string str(p);
   		cout << str;

2.string—> const char*

	string str="Hello World";
	const char *c = str.c_str();
	cout << c << endl;

3.const char*—> char*

	const char* tmp = "Hello World";
    char* p = const_cast<char*>(tmp);
    cout << p << endl;

4.char*—> const char*

	char* p = "Hello World";
    const char* temp = p;
    cout << temp << endl;
Published 17 original articles · won praise 14 · views 308

Guess you like

Origin blog.csdn.net/weixin_44635198/article/details/104507324