天天看點

自己實作atoi函數

#include <iostream>

#include <string>

using namespace std;

// 自己實作atoi函數的過程

int My_atoi(const char *  p);

int main()

{

string s;

cout << "請輸入一個字元串:";

cin >> s;

cout<<"經過轉換為整形為:"<<My_atoi(s.c_str())<<endl;

system("pause");

return 0;

}

int My_atoi(const char *  p)

{

int flag = 1 ,result = 0;

if (*p >= '0' && *p <= '9' || '-' == *p || '+' == *p)

if ('-' == p[0])

{

flag = -1;

p++;

}

else if ('+' == p[0])

p++;

while (*p <= '9' && *p >= '0')

result = 10 * result + (*p++ - '0');

return flag * result;

}