简体   繁体   English

在 C 中将 char 数组转换为 int 数

[英]Convert char array to a int number in C

I want to convert a char array[] like:我想转换一个字符数组[],如:

char myarray[4] = {'-','1','2','3'}; //where the - means it is negative

So it should be the integer: -1234 using standard libaries in C .所以它应该是整数:-1234 使用C 中的标准库。 I could not find any elegant way to do that.我找不到任何优雅的方法来做到这一点。

I can append the '\\0' for sure.我可以肯定地附加 '\\0' 。

I personally don't like atoi function.我个人不喜欢atoi功能。 I would suggest sscanf :我建议sscanf

char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);

It's very standard, it's in the stdio.h library :)这是非常标准的,它在stdio.h库中 :)

And in my opinion, it allows you much more freedom than atoi , arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.在我看来,它比atoi给你更多的自由,你的数字字符串的任意格式,并且可能还允许在最后使用非数字字符。

EDIT I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi , sscanf and strtol .编辑我刚刚在网站上发现了这个很好的问题,该问题解释并比较了 3 种不同的方法 - atoisscanfstrtol Also, there is a nice more-detailed insight into sscanf (actually, the whole family of *scanf functions).此外,还有对sscanf (实际上是整个*scanf函数系列)的更详细的了解。

EDIT2 Looks like it's not just me personally disliking the atoi function. EDIT2看起来不仅仅是我个人不喜欢atoi功能。 Here's a link to an answer explaining that the atoi function is deprecated and should not be used in newer code.这是一个答案的链接,解释了atoi函数已被弃用,不应在较新的代码中使用。

Why not just use atoi?为什么不直接使用atoi? For example:例如:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:正如预期的那样,给了我:

-123

Update: why not - the character array is not null terminated.更新:为什么不 - 字符数组不是空终止。 Doh!哦!

It isn't that hard to deal with the character array itself without converting the array to a string.在不将数组转换为字符串的情况下处理字符数组本身并不难。 Especially in the case where the length of the character array is know or can be easily found.特别是在字符数组的长度已知或很容易找到的情况下。 With the character array, the length must be determined in the same scope as the array definition, eg:对于字符数组,长度必须在与数组定义相同的范围内确定,例如:

size_t len sizeof myarray/sizeof *myarray;

For strings you, of course, have strlen available.对于字符串,您当然可以使用strlen

With the length known, regardless of whether it is a character array or a string, you can convert the character values to a number with a short function similar to the following:在已知长度的情况下,无论是字符数组还是字符串,都可以使用类似于以下的短函数将字符值转换为数字:

/* convert character array to integer */
int char2int (char *array, size_t n)
{    
    int number = 0;
    int mult = 1;

    n = (int)n < 0 ? -n : n;       /* quick absolute value check  */

    /* for each character in array */
    while (n--)
    {
        /* if not digit or '-', check if number > 0, break or continue */
        if ((array[n] < '0' || array[n] > '9') && array[n] != '-') {
            if (number)
                break;
            else
                continue;
        }

        if (array[n] == '-') {      /* if '-' if number, negate, break */
            if (number) {
                number = -number;
                break;
            }
        }
        else {                      /* convert digit to numeric value   */
            number += (array[n] - '0') * mult;
            mult *= 10;
        }
    }

    return number;
}

Above is simply the standard char to int conversion approach with a few additional conditionals included.以上只是标准的 char 到 int 转换方法,其中包含一些额外的条件。 To handle stray characters, in addition to the digits and '-' , the only trick is making smart choices about when to start collecting digits and when to stop.要处理杂散字符,除了digits'-' ,唯一的技巧是明智地选择何时开始收集数字以及何时停止。

If you start collecting digits for conversion when you encounter the first digit , then the conversion ends when you encounter the first '-' or non-digit .如果您在遇到第一个digit时开始收集digits以进行转换,则在遇到第一个'-'non-digit时转换结束。 This makes the conversion much more convenient when interested in indexes such as (eg file_0127.txt ).当对索引(例如file_0127.txt )感兴趣时,这使得转换更加方便。

A short example of its use:其使用的简短示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int char2int (char *array, size_t n);

int main (void) {

    char myarray[4] = {'-','1','2','3'}; 
    char *string = "some-goofy-string-with-123-inside";
    char *fname = "file-0123.txt";

    size_t mlen = sizeof myarray/sizeof *myarray;
    size_t slen = strlen (string);
    size_t flen = strlen (fname);

    printf ("\n myarray[4] = {'-','1','2','3'};\n\n");
    printf ("   char2int (myarray, mlen):  %d\n\n", char2int (myarray, mlen));

    printf (" string = \"some-goofy-string-with-123-inside\";\n\n");
    printf ("   char2int (string, slen) :  %d\n\n", char2int (string, slen));

    printf (" fname = \"file-0123.txt\";\n\n");
    printf ("   char2int (fname, flen)  :  %d\n\n", char2int (fname, flen));

    return 0;
}

Note: when faced with '-' delimited file indexes (or the like), it is up to you to negate the result.注意:当遇到'-'分隔的文件索引(或类似的)时,由您来否定结果。 (eg file-0123.txt compared to file_0123.txt where the first would return -123 while the second 123 ). (例如file-0123.txt相比file_0123.txt其中第一将返回-123 ,而第二123 )。

Example Output示例输出

$ ./bin/atoic_array

 myarray[4] = {'-','1','2','3'};

   char2int (myarray, mlen):  -123

 string = "some-goofy-string-with-123-inside";

   char2int (string, slen) :  -123

 fname = "file-0123.txt";

   char2int (fname, flen)  :  -123

Note: there are always corner cases, etc. that can cause problems.注意:总有一些极端情况等会导致问题。 This isn't intended to be 100% bulletproof in all character sets, etc., but instead work an overwhelming majority of the time and provide additional conversion flexibility without the initial parsing or conversion to string required by atoi or strtol , etc.这并不打算在所有字符集等中都是 100% 防弹,而是在绝大多数时间工作并提供额外的转换灵活性,而无需初始解析或转换为atoistrtol等所需的字符串。

So, the idea is to convert character numbers (in single quotes, eg '8') to integer expression.所以,这个想法是将字符数(在单引号中,例如'8')转换为整数表达式。 For instance char c = '8';例如 char c = '8'; int i = c - '0' //would yield integer 8; int i = c - '0' // 将产生整数 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.并按照908=9*100+0*10+8的原则将所有转换后的数相加,循环完成。

char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.

int s = 1;
int i = -1;
int res = 0;

if (c[0] == '-') {
  s = -1;
  i = 0;
}

while (c[++i] != '\0') { //iterate until the array end
  res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}

res = res*s; //answer: -908

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.这不是问题所问的问题,但我使用了@Rich Drummond 的答案来处理从标准输入读取的字符数组,该数组以空字符结尾。

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM