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

一级标题 c++ 数字类型和字符串类型互转

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

猜你喜欢

转载自blog.csdn.net/qq_53336225/article/details/120069097
今日推荐