2010-02-26 81 views

回答

11

使用isdigit

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

您需要

#include <ctype.h> 

确保isdigit可不管执行标准库的。

+0

失败对于以下数字:4,୬,1,9 – Bill 2010-02-26 21:01:06

+0

@Bill当然,但该示例是基于ascii数字要求的假设。我链接的页面解释了解决方案,如果程序员需要本地特定的数字,我不能再猜测程序员的要求。 – Yacoby 2010-02-26 23:52:33

+1

我理解你的假设,我只是没有看到原始问题中的任何内容来证明它们的正确性。 – Bill 2010-03-01 19:48:14

0

使用isdigit

if (isdigit(s.at(10)) { 
    ... 
} 
5

下面将告诉你:

isdigit(s.at(10)) 

将解析为 '真',如果在10位字符是一个数字。

您需要包含< ctype>。

+0

我不需要包含ctype,它仍然有效。 – neuromancer 2010-02-26 10:17:59

+5

在C++中,实现可能会设置它们的标头,使得一个标头包含另一个标头。 'std :: string'需要''这可能很好地在''带来了你的执行。这是巧合;你不能依靠那个。 – MSalters 2010-02-26 10:55:50

0

另一种方法是检查字符

if (s.at(10) >= '0' && s.at(10) <= '9') 
    // it's a digit 
+0

对于诸如4,୬,1,9等数字,此操作失败。 std :: isdigit是真实应用程序的更好选择:http://www.cplusplus.com/reference/std/locale/isdigit/ – Bill 2010-02-26 13:19:39

8

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

然后,你可以识别以下数字为位数:४, ੬, ൦, ௫, ๓, ໒

相关问题