C++實現int轉char*和char*轉int

#include <iostream>
#include <string.h>
using namespace std;

/***將字符串轉成int***/
int char2int(const char* str) {
    const char* p = str;
    bool neg = false;
    int res = 0;
    if (*str == '-' || *str == '+') {
        str++;
    }

    while (*str != 0) {
        if (*str < '0' || *str > '9') {
            break;
        }
        res = res * 10 + *str - '0';
        str++;
    }

    if (*p == '-') {
        res = -res;
    }
    return res;
}

/***將int轉成字符串***/
void int2char(int v, char* s) {
    int t = v < 0 ? -v : v;
    int i = 0;
    char buf[10] = "";
    while (t) {
        buf[i++] = t % 10 + '0';
        t = t / 10;
    }
    int len = v < 0 ? i+1 : i;
    for (int j = 0; j < i; j++) {
        s[j + len - i] = buf[i - j - 1];
    }
    s[len] = 0;
    if (len - i > 0) {
        s[0] = '-';
    }
    return;
}


int main()
{
    char s[10];
    snprintf(s, 10, "%s", "-1314520");

    int i = char2int(s);
    cout << i << endl;

    char str[10];
    int2char(9079968, str);
    cout << str << endl;

}

發佈了37 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章