简体   繁体   English

C ++中“ atoi”功能的简单示例

[英]Simple example of the “atoi” function in c++

Can someone please give a very simple example on how to use the atoi function? 有人可以举一个关于如何使用atoi函数的非常简单的示例吗? I know how it is supposed to work, but most of the examples are in objective C... Which I have trouble reading with since I haven't really learned it yet . 我知道它应该如何工作,但是大多数示例都在目标C中。由于我还没有真正学习它,因此我很难阅读。 Thanks, in advance! 提前致谢!

#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

Because behaviour in this last case is undefined (probably so some implementations can loop adding the next digit to ten times the previous value without spending time checking for signed integer overflow), it's recommended to use std::stoi or std::strtol instead. 由于后一种情况的行为是不确定的(可能因此某些实现可以将下一个数字循环添加到前一个值的十倍而无需花费时间检查有符号整数溢出),因此建议使用std::stoistd::strtol

See also: cppreference atoi for documentation including examples; 另请参见: cppreference atoi以获取包括示例的文档; stoi 斯托伊

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM