c++数字类型和字符串类型怎么互转

发布时间:2021-09-03 16:13:53 作者:chen
来源:亿速云 阅读:147

本篇内容介绍了“c++数字类型和字符串类型怎么互转”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

目录

一级目录 数字转为字符串

二级目录 字符串转为数字

1.数字转为字符串

(1).首先要加头文件

#include < iostream >

#include < sstream >

#include < string >

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

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

  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次

#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.字符串转数字

单个字符转为数字

我以前用过这种写法

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

字符串转为数字

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

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

#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()函数

//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
}

“c++数字类型和字符串类型怎么互转”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. Python:数字类型和字符串类型的内置方法
  2. python 数据类型 之 数字类型

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++中双冒号::的用法

下一篇:MySQL中的隐藏列的具体查看方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》