目录
一、数值转string
1.to_string()
1.1 头文件:
#include <string>
1.2 用法
基本支持所有类型数值的转换:
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
1.3 举例
// to_string example
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
输出结果:
pi is 3.141593
28 is a perfect number
2.osstream
2.1 头文件
#include <sstream>
2.2 用法
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ostringstream oss;
int a = 123;
oss << a;
string bStr = oss.str();
cout << bStr << endl;
oss << "abc";
bStr = oss.str();
cout << bStr << endl;
return 0;
}
输出结果:
123
123abc
二、string转数值
1.使用C语言的方法
1.1 string转int
int atoi (const char * str);
头文件:
#include <stdlib.h>
举例:
/* 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;
}
输出:
Enter a number: 23
The value entered is 23. Its double is 46.
1.2 string转long
long int atol ( const char * str );
头文件:
#include <stdlib.h>
举例:
/* atol example */
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atol */
int main ()
{
long int li;
char buffer[256];
printf ("Enter a long number: ");
fgets (buffer, 256, stdin);
li = atol(buffer);
printf ("The value entered is %ld. Its double is %ld.\n",li,li*2);
return 0;
}
输出:
Enter a number: 567283
The value entered is 567283. Its double is 1134566.
2.istringstream
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "123 456 789";
istringstream iss(a);
int i;
while (iss >> i) {
cout << i << endl;
}
}
输出:
123
456
789