[英]Convert char array to single int?
有人知道如何將char數組轉換為單個int嗎?
char hello[5];
hello = "12345";
int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
有多種方法可以將字符串轉換為 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");
解決方案 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
。
我用 :
int convertToInt(char a[1000]){
int i = 0;
int num = 0;
while (a[i] != 0)
{
num = (a[i] - '0') + (num * 10);
i++;
}
return num;;
}
使用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;
}
我將把這個留在這里給那些對沒有依賴關系的實現感興趣的人。
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;
}
適用於負值,但不能處理中間混合的非數字字符(雖然應該很容易添加)。 僅整數。
例如,“mcc”是一個字符數組,而“mcc_int”是您想要獲取的整數。
char mcc[] = "1234";
int mcc_int;
sscanf(mcc, "%d", &mcc_int);
使用 cstring 和 cmath:
int charsToInt (char* chars) {
int res{ 0 };
int len = strlen(chars);
bool sig = *chars == '-';
if (sig) {
chars++;
len--;
}
for (int i{ 0 }; i < len; i++) {
int dig = *(chars + i) - '0';
res += dig * (pow(10, len - i - 1));
}
res *= sig ? -1 : 1;
return res;
}
Ascii 字符串到整數的轉換是由atoi()
函數完成的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.