zoukankan      html  css  js  c++  java
  • 把字符串转换成整数

    题目:输入一个表示整数的字符串,把该字符串转换成整数并输出。例如输入字符串"345",则输出整数345。

    题目比较简单,但是涉及到许多问题,例如非法输入,有正负号,是否为空字符串等等 

    //把字符串转换成整数
    #include<iostream>
    #include<string>
    using namespace std;
    enum flag{
    	valid=0,
    	invalid
    };
    int judge=valid;
    int paraInt(string s){
    	long num=0;
    	int f=1;
    	if(s.empty()) judge=invalid;    //判断是否为空字符串
    	else{
    		string::size_type i=0;
    		if(s[0]=='+') {                  //正负号
    			i=1;
    			if(s.length()==1) judge=invalid;       //不加这步若字符串为"+"会输出0
    		}
    		if(s[0]=='-') {
    			i=1;
    			f=-1;
    			if(s.length()==1) judge=invalid;
    		}
    		for(i;i<s.length();i++){                  //转换
    			int temp=s[i]-'0';
    			if(temp>=0&&temp<=9)
    				num=num*10+temp;
    			else{
    				judge=invalid;
    				break;
    			}
    		}
    	}
    	num*=f;
    	return static_cast<int>(num) ;          //类型转换
    }
    int main(void){
    	string s;
    	cin>>s;
    	int num=paraInt(s);
    	if(!judge) cout<<num<<endl;
    	else cout<<"invalid input"<<endl;
    	system("pause");
    	return 0;
    }
    
     

  • 相关阅读:
    HTML 拖放 和 地理定位
    HTML web存储
    HTML 语义元素 和 MathML元素
    Docker Swarm
    Docker Machine
    Docker Compose
    Docker 的网络模式
    数据共享与持久化
    镜像和容器的基本操作
    Docker 简介
  • 原文地址:https://www.cnblogs.com/aLittleBitCool/p/1957202.html
Copyright © 2011-2022 走看看