zoukankan      html  css  js  c++  java
  • 字符串与数字转换

    1. itoa,非标准的C语言扩展函数,头文件为 #include<stdlib.h>

    char* itoa (int value, char* string, int radix);

    #include<algorithm>
    #include<cstdlib>
    #include<cstring>
    using namespace std;
    
    int main(){
    	char str[10];
    	int n=12345;
    	itoa(n,str,10);
    	cout<<str[2]<<endl;
    	string newStr(str);
    	cout<<newStr[3]<<endl;
    	
    
    	return 0;
    }

    2. springf,格式化数据到字符串缓冲区,头文件为 #include<stdlib.h>

    int sprintf( char *buffer, const char *format, [ argument] … );

    #include<stdio.h>
    #include<stdlib.h>
    int main()
    {
    	char buffer[50];
    	int n,a=5,b=3;
    
    	n = sprintf(buffer,"%dplus%dis%d",a,b,a+b);
    
    	printf("[ %s ] is a string %d chars long
    ",buffer,n);/*“格式输出”*/
    	 
    	return 0;
    }

    3.  atoi,C库函数, 将字符串变为数字,头文件为 #include<stdlib.h>

    int atoi(const char *nptr);

    #include<stdlib.h>
    #include<stdio.h>
    
    int main(void)
    {
    	double n;
    	char*str="12345.67";
    	n=atoi(str);
    	printf("string=%s integer=%d
    ",str,(int)n);
    	return 0;
    }

    4. 写一个atoi的实现函数

    #include <iostream>
    using namespace std;
    
    void main(void){
    	char str[20];      
    	int i,n=0;	
    
    	cout<<"Enter the string:";         
    	cin.getline(str,20,'
    ');
    	
        for (i=0; str[i] != ''; i++) 
    		n = n*10+(str[i]-'0');
    
    	cout<<"Corresponding number is "<<n<<endl;
    
        cout<<"The digits of the number from low to high is ";
    	while(n){
    		cout<<n%10<<',';   
    		n/=10;
    	}
    	cout<<endl;
    }
    





  • 相关阅读:
    网页返回码大全
    求数组中子数组的最大和
    什么是面向对象?面向对象与面向过程的区别?
    Java内部类
    Java拆箱装箱
    linux中su和sudo区别
    Linux 中账户管理
    解决warn appiumdoctor bin directory for $java_home is not set
    Moco之include
    Mock server 之 Moco的使用
  • 原文地址:https://www.cnblogs.com/sjw1357/p/3864022.html
Copyright © 2011-2022 走看看