可视化 C++ 中 "atoi" 函数的简单示例

visual Simple example of the "atoi" function in c++

本文关键字:简单 atoi C++ 可视化 函数      更新时间:2023-10-16

有人可以举一个非常简单的例子来说明如何使用 atoi 函数吗?我知道它应该如何工作,但大多数例子都在客观 C 中......我很难阅读,因为我还没有真正学会它. 谢谢,提前!

#include <cstdlib>        // wraps stdlib.h in std, fixes any non-Standard content
std::string t1("234");
int i1 = std::atoi(t1.c_str());
int i1b = std::stoi(t1);  // alternative, but throws on failure
const char t2[] = "123";
int i2 = std::atoi(t2);
const char* t3 = "-93.2"; // parsing stops after +/- and digits
int i3 = std::atoi(t3);   // i3 == -93
const char* t4 = "-9E2";  // "E" notation only supported in floats
int i4 = std::atoi(t4);   // i4 == -9
const char* t5 = "-9 2";  // parsing stops after +/- and digits
int i5 = std::atoi(t5);   // i5 == -9
const char* t6 = "ABC";   // can't convert any part of text
int i6 = std::atoi(t6);   // i6 == 0 (whenever conversion fails completely)
const char* t7 = "9823745982374987239457823987";   // too big for int
int i7 = std::atoi(t7);   // i7 is undefined

由于最后一种情况下的行为是未定义的(可能是某些实现可以循环将下一个数字添加到前一个值的十倍,而无需花时间检查有符号整数溢出),因此建议改用std::stoistd::strtol

另请参阅:cpp首选项 atoi 用于包括示例在内的文档;stoi