c ++中“atoi”函数的简单示例

时间:2014-04-07 01:18:26

标签: c++ visual-c++ atoi

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

1 个答案:

答案 0 :(得分:3)

#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::stoi或{{ 1}}而不是。

另请参阅:cppreference atoi了解包含示例的文档; stoi