服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - c++ 数字类型和字符串类型互转详解

c++ 数字类型和字符串类型互转详解

2021-12-29 14:01Easyhappy. C/C++

今天小编就为大家分享一篇讲解c++ 数字类型和字符串类型互转的文章,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

一级目录 数字转为字符串

二级目录 字符串转为数字

1.数字转为字符串

(1).首先要加头文件

#include < iostream >

#include < sstream >

#include < string >

这个类在头文件中定义, < sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。

实现这个目标,非stringstream类莫属;

?
1
2
3
4
5
6
int i=100.22;
//用 stringstream定义一个变量 str;
stringstream s;
s<<i;  //这不是输出语句!
string str1=s.str();
//str1即为转为的字符串

写个例题 //来自牛客网上的一题

输入一个整数 n ,求1~n这n个整数的十进制表示中1出现的次数

例如,1~13中包含1的数字有1、10、11、12、13因此共出现6次

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int NumberOf1Between1AndN_Solution(int n)
{
        int count=0;
        for(int i=1;i<=n;i++)
        {
            stringstream s;
            s << i;
             string str=s.str();
            for(int j=0;j<str.size();j++)
            {
               if(str[j]=='1')
               {
                     count++;
               }
            }
        }
        return count;
}
int main()
{
   int a=13;
   int count=NumberOf1Between1AndN_Solution(a);
   cout<<count;
   return 0;
 }

1.字符串转数字

单个字符转为数字

我以前用过这种写法

?
1
2
string  str="3434";
int a=str[1]-'0'; //a=4;

字符串转为数字

可自己按照单个字符转的方式自己写一个函数

?
1
2
3
4
5
6
7
8
string s="321";
int num=0;
for(int i=0; i<s.size() ;i++){
    //把单个字符变为数字
    int x= s[i]-'0';
    //每次都要进位,也就是*10
    num = num*10 + x;
}

还可以用< sstream >里的stringstream

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
     string str="342324";
     int a;
     stringstream ss;
     ss<<str;
     ss>>a;
     cout<<a-1;//输出342323
     return 0;
}

还可以用 #include<stdlib.h>头文件下atoi()函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//string  转为int
//string 利用从   .c_str() 转  const char *
//利用atoi(const char * ) 转 int
#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
int main()
{
    string str="3413414";
    int a=atoi(str.c_str());
    cout<<a-1;
    return 0; //输出3413413
}

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/qq_53336225/article/details/120069097

延伸 · 阅读

精彩推荐