码迷,mamicode.com
首页 > 其他好文 > 详细

字符串转换为数字

时间:2015-05-04 19:35:21      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

int 型数据的范围:-2^31~2^31-1(-2147483648~2147483647)

unsigned int:  0~2^32

1.自己写的函数,注意特殊情况的考虑

#include <iostream>
    using namespace std;
#include <climits>     //包含整型数的范围限制

int StrToInt(char *s)
{
    unsigned long int number=0;
    bool ifneg=false;
    if(s==nullptr)               //需要对空字符串进行处理
    {
        cout<<"字符串为空";
        return 0;
    }
    else
    {
        while(*s== ||*s==\n||*s==\r||*s==\t||*s==f||*s==\b)   //扫描前面的空格,跳过空格
        {++s;}
        if(*s==45)
        {ifneg=true;
        ++s;}          //首字母为负号
        else if(*s==43)
        {++s;}
        while(*s!=0)        //c风格字符串以空字符(\0)结尾,空字符的ASCII码为0。cout打印时看到空字符才结束
        {
            if(*s<0||*s>0+9)
            {
                cout<<"存在非数字字符";      //需要考虑存在非数字字符的情况
                return 0;
            }
            number=number*10+*s-0;
            ++s;
            if(ifneg==false&&number>INT_MAX)             //对溢出进行处理
            {
                cout<<"数字溢出,结果为:"<<INT_MAX;
                return INT_MAX;
            }
            else if(ifneg==true&&number-1>INT_MAX)
            {
                cout<<"数字溢出,结果为:"<<INT_MIN;
                return INT_MIN;
            }
        }
        if(ifneg==true)
            {cout<<(int)-number;
            return (int)-number;}
        else
        {cout<<(int)number;
            return (int)number;}
    }
}

void main()
{
    char s[100];
    cin>>s;
    StrToInt(s);
}

 2.c语言中的sscanf

#include<iostream>
using namespace std;
#include<stdio.h>
void main()
{
    char s[100];
    cin>>s;
    int i;
    float f;
    sscanf(s,"%d",&i);    //溢出的时候会用负值来表示
    sscanf(s,"%f",&f);
    cout<<"i:"<<i<<endl;
    cout<<"f:"<<f;
}

3.c标准库中的atoi

#include<iostream>
using namespace std;
#include<stdio.h>
void main()
{
    char s[100];
    cin>>s;
    int i;
    float f;
    i=atoi(s);    //存在非数字的字符时也会输出0,溢出时会得到INT_MAX
    f=atof(s);    //科学计数法来表示结果
    cout<<"i:"<<i<<endl;
    cout<<"f:"<<f;
}
#include<iostream>
using namespace std;
#include<string>
void main()
{
    string s;
    cin>>s;
    int i;
    float f;
    i=atoi(s.c_str());    //存在非数字的字符时也会输出0,溢出时会得到INT_MAX
    f=atof(s.c_str());    //科学计数法来表示结果
    cout<<"i:"<<i<<endl;
    cout<<"f:"<<f;
}

 

字符串转换为数字

标签:

原文地址:http://www.cnblogs.com/wy1290939507/p/4476932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!