zoukankan      html  css  js  c++  java
  • C++int转化为string类型;string转化为int类型2

     1 #include <iostream>
     2 #include <string>
     3 #include <vector>
     4 #include <fstream>
     5 #include <sstream>
     6 
     7 using namespace std;
     8 
     9 string int2str(int number)
    10 {
    11     string strNumber;
    12     int result = abs(number);                                                               
    13 
    14     if (result == 0)
    15     {
    16         strNumber = "0";
    17     }
    18     else
    19     {
    20         while (result)
    21         {
    22             strNumber = (char)(result % 10 + '0' ) + strNumber;
    23             result /= 10;
    24         } 
    25     }
    26 
    27     if (number < 0)
    28         strNumber = "-" + strNumber;
    29 
    30     return strNumber;
    31 }
    32 
    33 int main(int argc, char *argv[])
    34 {
    35     string strNumber = int2str(-797);
    36     cout << strNumber << endl;
    37 
    38     return 0;
    39 }

    这里是将int转化为string类型,思路是将int型数据除以10得到从而得到每一位。

     1 #include <iostream>
     2 #include <string>
     3 #include <vector>
     4 #include <fstream>
     5 #include <sstream>
     6 
     7 using namespace std;
     8 
     9 int str2int(const string& strNumber)
    10 {
    11     if (strNumber.length() == 0)
    12     {
    13         cout << "Input error!" << endl;
    14         return -1;
    15     }
    16 
    17     string tmpStr(strNumber);
    18     if (tmpStr[0] == '-')
    19         tmpStr.assign(tmpStr.begin() + 1, tmpStr.end());
    20     
    21     int number = 0;
    22     for (size_t i = 0; i < tmpStr.length(); i++)
    23     {
    24         number = number * 10 + (tmpStr[i] - '0');
    25     }
    26 
    27     if (strNumber[0] == '-')
    28         number *= -1;
    29 
    30     return number;
    31 }
    32 
    33 int main(int argc, char *argv[])
    34 {
    35     int number = str2int(string("-70865"));
    36     cout << number << endl;
    37 
    38     return 0;
    39 }

    将string转化为int类型。

  • 相关阅读:
    根分区/tmp满了,卸载home添加给根分区
    Docker容器技术教程
    使用vscode访问和编辑远程服务器文件
    使用 VS Code 远程连接Linux服务器告别xshell
    Docker安装参考文档记录
    yolov5在Centos系统上部署的环境搭建
    YOLOV5四种网络结构的比对
    k8s部署kube-state-metrics组件
    Kubernetes集群部署Prometheus和Grafana
    Prometheus介绍
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3038527.html
Copyright © 2011-2022 走看看