*** 自写代码:字符串转数字

include <iostream>
#include <string.h>
using namespace std;
bool strToInt (char * strIn, int * valueOut)
{
    if ((strIn==NULL) || (valueOut==NULL))
    {
        return false;
    }
    bool status = false;
    int  value = 0;
    int  i = (strIn[0]=='-')?(1):(0);
    while (strIn[i]>='0' && strIn[i]<='9')
    {
        value = value*10 + strIn[i] - '0';
        i++;
    }
    status = (i==strlen(strIn))?(true):(false);
    if (status)
    {
        *valueOut = (strIn[0]=='-')?(0-value):(value);
    }
    else
    {
        valueOut = NULL;
    }
    return status;
}
int main()
{
    char s[20] = "";
    int value;
    cin.getline (s, 20);    
    if (strToInt(s, &value))
    {
        cout << "input: " << value << endl;
    }
    else
    {
        cout << "Failure!\n" << endl;
    }
    return 0;
}

 

posted @ 2018-12-23 19:12  super行者  阅读(148)  评论(0编辑  收藏  举报