任何人都知道如何將char數組轉換爲單個int?將char數組轉換爲單個int?
char hello[5];
hello = "12345";
int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
任何人都知道如何將char數組轉換爲單個int?將char數組轉換爲單個int?
char hello[5];
hello = "12345";
int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
長話短說,你必須使用atoi()
編輯:
如果你有興趣做這個the right way:
char szNos[] = "12345";
char *pNext;
long output;
output = strtol (szNos, &pNext, 10); // input, ptr to next char in szNos (null here), base
ASCII字符串到整數的轉換是由完成atoi()
功能。
這是你應該避免的。你如何檢查錯誤? – 2011-05-23 08:37:15
使用sscanf
/* sscanf example */
#include <stdio.h>
int main()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i;
sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);
return 0;
}
不管怎樣,都不是這樣。例如,不要使用'「%s」',因爲這會導致緩衝區溢出。總而言之,'stdtol'更簡單,更安全。 – 2011-05-23 08:39:39
是不是'strtol'?爲什麼'strtol'比'atoi'好? – qed 2013-11-06 20:43:29
有一個字符串轉換爲一個int的多張的方式。
解決方案1:使用傳統C功能
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
解決方案2:使用lexical_cast
(最適當&簡單)
int x = boost::lexical_cast<int>("12345");
SOLU重刑3:使用C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
如果您正在使用C++11
,你應該使用stoi
,因爲它可以錯誤和解析"0"
區分。
try {
int number = std::stoi("1234abc");
} catch (std::exception const &e) {
// This could not be parsed into a number so an exception is thrown.
// atoi() would return 0, which is less helpful if it could be a valid value.
}
應當指出的是,「1234abc」是被傳遞到stoi()
前char[]
到std:string
implicitly converted。
我會在這裏留給這個對沒有依賴關係的實現感興趣的人。
inline int
stringLength (char *String)
{
int Count = 0;
while (*String ++) ++ Count;
return Count;
}
inline int
stringToInt (char *String)
{
int Integer = 0;
int Length = stringLength(String);
for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10)
{
if (String[Caret] == '-') return Integer * -1;
Integer += (String[Caret] - '0') * Digit;
}
return Integer;
}
適用於負值,但不能處理混合在其間的非數字字符(應該很容易添加)。只有整數。
該代碼是否按原樣編譯?它不應該。 – 2011-05-23 06:09:00
這不應該。 convert_char_to_int(hello)不是一個實際的函數。我問什麼函數/方法我應該用來取代我的理論:「convert_char_to_int(hello)」? – IsThisTheEnd 2011-05-23 06:10:44
'hello'是一個不可修改的*左值*所以'hello =「12345」;'甚至不會編譯。 – 2011-05-23 06:10:53