面試題33 把字串轉換為整數

2021-06-17 21:06:56 字數 1460 閱讀 3022

c語言的庫函式atoi()的作用是將乙個字串轉換為整數。寫乙個函式strtoint,實現這一功能。

// 寫乙個函式strtoint實現將字串轉換為整數的功能.cpp : 定義控制台應用程式的入口點。

#include "stdafx.h"

#include using namespace std;

//特殊情況:1.字串為空指標或空串

//2.字串中有非0到9的字元(負號,#,@,等等)

//特別需要注意的是:還要考慮溢位的問題。正整數最大值0x7fffffff,負整數最小值0x80000000

//函式功能:將字串str轉換為整數, 由引數nint接收整數值,若轉換成功返回true,否則返回false

bool strtoint(char *str, int &nint)

else if (str == null)

else if ((strcmp(str, "+")==0) || (strcmp(str, "-")==0))

else

else if (isfirst && (*p)=='+')

if ((*p) >='0' && (*p) <= '9')//當前字元為數字字元

p++;

}else//當前字元為非數字字元

} if (hasminus)//字串有負號

return true;

}

}int _tmain(int argc, _tchar* argv)

if (ntest2 < (signed int)0x80000000)

int nint = 0;

char *str = null;

if (strtoint("123", nint))

if (strtoint("", nint))//空串

if (strtoint(str, nint))//空指標

if (strtoint("-123", nint))

if (strtoint("+123", nint))

if (strtoint("-12#3@", nint))

if (strtoint("0", nint))

if (strtoint("+", nint))

if (strtoint("100000000000000000000000000000000000000", nint))

if (strtoint("-100000000000000000000000000000000000000", nint))

system("pause");

return 0;

}

執行結果:

說明:在判斷上溢、下溢時出現錯誤!不知緣由,請大牛指正!

面試題53 把字串轉換為整數

題目 把字串轉換為整數。思路 這題不難,注意邊界條件及異常。成員變數的初始化順序是怎樣的?下面 的輸出 include include using namespace std class a void print cout n1 n1 n2 n2 分析 1 成員變數在使用初始化列表初始化時,與建構函...

把字串轉換為整數

題目 將乙個字串轉換成乙個整數,要求不能使用字串轉換整數的庫函式。數值為0或者字串不是乙個合法的數值則返回0 思路 若為負數,則輸出負數,字元0對應48,9對應57,不在範圍內則返回0,並列印錯誤資訊 public class strtoint public static int strtoint ...

C語言把整數轉換為字串

各位可能在網上看到用以下函式可以將整數轉換為字串 itoa 將整型值轉換為字串 ultoa 將無符號長整型值轉換為字串 請注意,上述函式與ansi標準是不相容的,很多編譯器根本不提供這幾個函式,本文就不介紹了,沒什麼意義。將整數轉換為字串而且能與ansi標準相容的方法是使用sprintf 和snpr...