C 库 - atoi() 函数



C 的stdlibatoi() 函数用于将数字字符串转换为整数值。

整数是一个可以是正数或负数(包括零)的整数。它不能是分数、小数或百分比,例如,1、2、-5 和 -10 等数字是整数。

语法

以下是 c atoi() 函数的语法 -

int atoi(const char *str)

参数

此函数接受一个参数 -

  • str - 它是指向空终止字符串的指针,表示一个整数。

返回值

此函数返回一个整数,表示 int 值。如果输入字符串不是有效的字符串数字,则返回 0。

示例 1

以下是使用 atoi() 将字符串值转换为整数值的基本 c 示例。

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   int val;
   char *str; 
   str = "1509.10E";
   val = atoi(str); 
   printf("integral number = %d", val);
}

输出

以下是输出 -

integral number = 1509

示例 2

下面的 c 示例连接两个字符串,然后使用 atoi() 将结果字符串转换为整数。

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

int main() {	
   // Define two strings to concatenate
   char str1[] = "2023";
   char str2[] = "2024";
   
   //calculate the length of string first + second
   int length = strlen(str1) + strlen(str2) + 1;

   // Allocate memory for the concatenated string
   char *concatenated = malloc(length);

   // check memory allocation if null return 1.
   if(concatenated == NULL) {
       printf("Memory allocation failed\n");
       return 1;
   }

   // Concatenate str1 and str2
   strcpy(concatenated, str1);
   strcat(concatenated, str2);

   // Convert concatenated string into a integral number.
   // use the atoi() function
   int number = atoi(concatenated);

   printf("The concatenated string is: %s\n", concatenated);
   printf("The integral number is: %d\n", number);

   // at the last free the alocated memory
   free(concatenated);
   return 0;
}

输出

以下是输出 -

The concatenated string is: 20232024
The integral number is: 20232024

示例 3

以下是 atoi() 的另一个示例,这里我们将字符字符串转换为整数。

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

int main () {
   int res;
   char str[25];
   
   //define a string
   strcpy(str, "tutorialspoint India");
   
   //use atoi() function
   res = atoi(str);
   printf("String Value = %s\n", str);
   printf("Integral Number = %d\n", res);
   
   return(0);
}

输出

以下是输出 -

String Value = tutorialspoint India
Integral Number = 0
广告

© . All rights reserved.