21xrx.com
2024-09-20 00:07:02 Friday
登录
文章检索 我的文章 写文章
C++中的stoi和atoi函数简介
2023-07-01 02:58:26 深夜i     --     --
C++ stoi函数 atoi函数 简介 函数区别

在C++编程中,数字字符串和数字之间的转换是一个很普遍的任务。C++中有两个非常有用的函数,可以做到这一点:stoi和atoi函数。

stoi函数的作用是将一个字符串转换为一个整数。它的原型如下:


int stoi (const string& str, size_t* idx = 0, int base = 10);

其中,参数str是要转换的字符串;参数idx是一个指针,用于返回转换后字符串的最后一个字符的下标;参数base指定输入的数字是几进制的,默认值是10。

下面是一个使用stoi函数的例子:


#include <iostream>

#include <string>

int main ()

{

 std::string str_dec = "2001, A Space Odyssey";

 std::string str_hex = "40c3";

 std::string str_bin = "-10010110001";

 std::string str_auto = "0x7f";

 std::cout << std::stoi(str_dec) << '\n'

      << std::stoi(str_hex, nullptr, 16) << '\n'

      << std::stoi(str_bin, nullptr, 2) << '\n'

      << std::stoi(str_auto, nullptr, 0) << '\n';

 return 0;

}

上面的代码演示了如何将不同进制的数字字符串转换为整数。

另一个常用的函数是atoi函数。它从一个C字符串中提取整数。它的原型如下:


int atoi (const char* str);

其中,参数str是要转换为整数的字符串。

下面是一个使用atoi函数的例子:


#include <iostream>

#include <cstdlib>

int main ()

{

 const char* str = "10 2000000000000000000 hello 42";

 char* pEnd;

 long int li1, li2;

 li1 = std::strtol(str, &pEnd, 10);

 li2 = std::strtol(pEnd, &pEnd, 10);

 std::cout << "The decimal part is: " << li1 << '\n';

 std::cout << "The hexadecimal part is: " << std::hex << li2 << '\n';

 return 0;

}

上面的代码演示了如何使用atoi函数将字符串中的数字提取出来。

综上所述,stoi和atoi函数是C++中非常有用的函数,它们可以帮助我们在字符串和数字之间进行转换,提高我们的编程效率。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复