C++中数值和string互相转换的方法

一、数值转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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值