C++ 将char数组转换为单个int?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6093414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:29:13  来源:igfitidea点击:

Convert char array to single int?

c++charint

提问by IsThisTheEnd

Anyone know how to convert a char array to a single int?

有人知道如何将char数组转换为单个int吗?

char hello[5];
hello = "12345";

int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);

回答by Alok Save

There are mulitple ways of converting a string to an int.

有多种方法可以将字符串转换为 int。

Solution 1: Using Legacy C functionality

解决方案 1:使用传统 C 功能

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}

Solution 2: Using lexical_cast(Most Appropriate & simplest)

解决方案 2:使用lexical_cast(最合适和最简单)

int x = boost::lexical_cast<int>("12345"); 

Solution 3: Using C++ Streams

解决方案 3:使用 C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

回答by Rick Smith

If you are using C++11, you should probably use stoibecause it can distinguish between an error and parsing "0".

如果您正在使用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.
}

It should be noted that "1234abc" is implicitly convertedfrom a char[]to a std:stringbefore being passed to stoi().

应当指出的是,“1234abc”被隐式转换char[]一个std:string被传递到前stoi()

回答by Rick Smith

Use sscanf

使用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;
}

回答by Holly

I'll just leave this here for people interested in an implementation with no dependencies.

我将把这个留在这里给那些对没有依赖关系的实现感兴趣的人。

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;
    }

Works with negative values, but can't handle non-numeric characters mixed in between (should be easy to add though). Integers only.

适用于负值,但不能处理中间混合的非数字字符(虽然应该很容易添加)。仅整数。

回答by Tr?n Hi?p

I use :

我用 :

int convertToInt(char a[1000]){
    int i = 0;
    int num = 0;
    while (a[i] != 0)
    {
        num =  (a[i] - '0')  + (num * 10);
        i++;
    }
    return num;;
}

回答by Reno

Long story short you have to use atoi()

长话短说你必须使用atoi()

ed:

编:

If you are interested in doing this 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 

回答by harper

Ascii string to integer conversion is done by the atoi()function.

Ascii 字符串到整数的转换是由atoi()函数完成的。