C/C++ ATOI()函数教程——将字符串转换为整数

C和C++编程语言提供字符串或字符到整数转换 atoi() 功能。 atoi 简而言之,就是大写字母并排排列的简写形式。这个函数是由标准库提供的,这意味着我们不需要安装额外的库或包。

null

函数语法

atoi() 函数的语法非常简单。

int atoi (const char * str);
  • int 返回值的类型。
  • const char * 是一个常量字符数组,等于变量名为的字符串 str .

在C中包含 标题

atoi 函数是由标准库提供的,标准库为应用程序开发提供了基本的和流行的函数。因此,为了使用atoi()函数stdlib.h,应该包括如下头部。

#include 

在C++中包含 标头

在C++中 atoi() 函数可以与 cstdlib 标题或库。所以为了使用 atoi() 函数在C++中,我们应该包括这个头。

#include 

在C和C++中将字符串/字符转换为整数

我们将从一个简单的示例开始,在这个示例中,我们将以字符串或字符格式转换数字。在本例中,我们将把“1234”字符串转换为整数。如我们所见,“1234”字符串由4个数字组成,可以存储在 int 或整数变量。

C类:

/* String To Integer with atoi() function */#include       /* printf, fgets */#include      /* atoi */int main (){  int i;  char num[4] = "1234";  i = atoi (num);  printf ("The value entered is %d.",i);  return 0;}

C++:

/* String To Integer with atoi() function */#include       /* printf, fgets */#include      /* atoi */int main (){  int i;  char *num = "1234";  i = atoi (num);  printf ("The value entered is %d.",i);  return 0;}

将字符串/字符转换为负整数

在上一个示例中,我们已将表示正数的字符串转换为整数类型。我们也可以将一个负数转换成整数。在本例中,我们将“-4321”字符串转换为整数。请记住,在负数的字符串表示形式中有5个字符,因此字符数组或字符串的长度将为5个字符。

C类:

/* String To Integer with atoi() function */#include       /* printf, fgets */#include      /* atoi */int main (){  int i;  char num[5] = "-1234";  i = atoi (num);  printf ("The value entered is %d.",i);  return 0;}

C++:

/* String To Integer with atoi() function */#include       /* printf, fgets */#include      /* atoi */int main (){  int i;  char *num = "-1234";  i = atoi (num);  printf ("The value entered is %d.",i);  return 0;}

更多atoi()函数示例

我们已经检查了 atoi() 函数,但将字符串或字符整数转换为整数数据类型可能有一些复杂且难以理解的情况。

#include #include int main(){    const char *str1 = "57";    const char *str2 = "314.159";    const char *str3 = "52345 some text";    const char *str4 = "some text 25";    int mynum1 = std::atoi(str1);    int mynum2 = std::atoi(str2);    int mynum3 = std::atoi(str3);    int mynum4 = std::atoi(str4);    std::cout << "atoi("" << str1 << "") is " << mynum1 << '';    std::cout << "atoi("" << str2 << "") is " << mynum2 << '';    std::cout << "atoi("" << str3 << "") is " << mynum3 << '';    std::cout << "atoi("" << str4 << "") is " << mynum4 << '';}

输出如下。

More atoi() Function Examples
更多atoi()函数示例

我们可以看到关于将字符串或字符数组转换为整数有一些规则,我们可以在下面列出它们。

  • 如果给定的字符串或字符数组是类似“314.159”的浮点  只转换整数部分,其中结果为“314”
  • 如果在给定的字符数组或字符串中有一些非数字字符,它们将不会转换,并且只转换整数部分时不会出现错误。例如“52345 some text”将被转换为52345
  • 如果字符数组或字符串的开头和后面有数字字符,这将转换为0作为整数值。例如,“some text 25”将转换为0。
  • 如果数字字符介于非数字字符之间,则转换结果也将为0。
  • 如果字符数组或字符串以数字字符开头,并且其后有一个非数字字符,则仅转换起始数字字符。例如,“25文本50”将转换为25。
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享