如何确定字符串中的字符是否为整数

neu*_*cer 5 c++ string numbers

假设我想看一下字符串s中第10位的字符.

s.at(10);

知道这是一个数字最简单的方法是什么?

Yac*_*oby 13

使用isdigit

std::string s("mystring is the best");
if ( isdigit(s.at(10)) ){
    //the char at position 10 is a digit
}
Run Code Online (Sandbox Code Playgroud)

你会需要

#include <ctype.h>
Run Code Online (Sandbox Code Playgroud)

isdigit无论标准库的实现如何,都可以确保可用.

  • 我理解你的假设,我只是没有在原来的问题中看到任何可以证明它们合理性的内容。 (2认同)

Bil*_*ill 8

其他答案假设您只关心以下字符:0, 1, 2, 3, 4, 5, 6, 7, 8, 9.如果您正在编写可能在使用其他数字系统的语言环境中运行的软件,那么您将需要使用std::isdigit位于以下位置的新软件<locale>:http://www.cplusplus.com/reference/std/locale/isdigit/

然后您可以将以下数字识别为数字: ?, ?, ?, ?, ?, ?


And*_*rew 5

以下内容将告诉您:

isdigit( s.at( 10 ) )
Run Code Online (Sandbox Code Playgroud)

如果位置10的字符是数字,则将解析为"true".

您需要包含<ctype>.

  • 在C++中,实现可以设置它们的头部,使得一个头部包括另一个头部.`std :: string`需要`<string>`这很可能会在你的implementation_中引入`<ctype>`_.这是巧合; 你不能依赖它. (5认同)