在 C++ 中将字符串转换为整数

2022-01-14 00:00:00 string integer c++

你好我知道有人问了很多次,但我没有找到具体问题的答案.

Hello I know it was asked many times but I hadn't found answer to my specific question.

我只想转换只包含十进制数字的字符串:

I want to convert only string that contains only decimal numbers:

例如 256 可以,但 256a 不行.

For example 256 is OK but 256a is not.

不检查字符串可以吗?

谢谢

推荐答案

我能想到的使错误检查成为可选的最简单方法是:

The simplest way that makes error checking optional that I can think of is this:

char *endptr;
int x = strtol(str, &endptr, 0);
int error = (*endptr != '');

相关文章