字符串转整型

// exam.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<stdio.h>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;

int str2int(const char *str)
{
    int temp = 0;
    //ptr保存str字符串开头
    const char *ptr = str;
    //如果第一个字符是正负号,则移到下一个字符
    if (*str == '-' || *str == '+')
    {
        str++;
    }
    while (*str != '\0')
    {
        //如果当前字符不是数字,就退出
        if ((*str < '0') || (*str > '9'))
        {
            break;
        }
        //计算成整数
        temp = temp * 10 + (*str - '0');
        str++;
    }
    //针对负数处理
    if (*ptr == '-')
    {
        temp = -temp;
    }
    return temp;
}


int main()
{    
    char c[100];
    cin >> c;
    cout << "the numble is "<<str2int(c) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/guiwukejiBGG/article/details/82315846