strtol的基础知识? [英] Basics of strtol?

查看:164
本文介绍了strtol的基础知识?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑。我必须遗漏一些相当简单的东西,但我读到的关于strtol()的任何内容都没有意义。有人能以一种非常基本的方式为我拼出它,并举例说明我可能会得到以下内容吗?

I am really confused. I have to be missing something rather simple but nothing I am reading about strtol() is making sense. Can someone spell it out for me in a really basic way, as well as give an example for how I might get something like the following to work?

string input = getUserInput;
int numberinput = strtol(input,?,?);


推荐答案

第一个参数是字符串。它必须作为C字符串传入,所以如果你有 std :: string 使用 .c_str()首先。

The first argument is the string. It has to be passed in as a C string, so if you have a std::string use .c_str() first.

第二个参数是可选的,并指定一个 char * 来存储指向该字符的指针数字的结尾。这在转换包含多个整数的字符串时很有用,但如果您不需要它,只需将此参数设置为NULL。

The second argument is optional, and specifies a char * to store a pointer to the character after the end of the number. This is useful when converting a string containing several integers, but if you don't need it, just set this argument to NULL.

第三个参数是基数(基数) ) 转换。 strtol 可以通过二进制执行任何操作( base 2)to base 36.如果你想 strtol 根据前缀自动选择基数,请传入0。

The third argument is the radix (base) to convert. strtol can do anything from binary (base 2) to base 36. If you want strtol to pick the base automatically based on prefix, pass in 0.

所以,最简单的用法是

long l = strtol(input.c_str(), NULL, 0);

如果你知道你得到十进制数字:

If you know you are getting decimal numbers:

long l = strtol(input.c_str(), NULL, 10);

strtol 如果没有可兑换则返回0字符串开头的字符。如果你想检查 strtol 是否成功,请使用中间参数:

strtol returns 0 if there are no convertible characters at the start of the string. If you want to check if strtol succeeded, use the middle argument:

const char *s = input.c_str();
char *t;
long l = strtol(s, &t, 10);
if(s == t) {
    /* strtol failed */
}






如果您使用的是C ++ 11,请使用 stol

long l = stol(input);

或者,你可以使用 stringstream ,它具有能够轻松读取多个项目的优点,如 cin

Alternately, you can just use a stringstream, which has the advantage of being able to read many items with ease just like cin:

stringstream ss(input);
long l;
ss >> l;

这篇关于strtol的基础知识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆