猿问

如何检查给定的c ++字符串或char *是否仅包含数字?

或通过另一种方法找到第一个非数字字符。

相同的函数适用于string和char *吗?


缥缈止盈
浏览 809回答 3
3回答

繁星淼淼

在cctype头文件中有相当数量的,你可以在字符串中的每个字符使用字符分类功能。对于数字检查,应为isdigit。以下程序显示了如何检查C或C ++字符串的每个字符(就检查实际字符而言,该过程几乎是相同的,唯一真正的区别是如何获得长度):#include <iostream>#include <cstring>#include <cctype>int main (void) {&nbsp; &nbsp; const char *xyzzy = "42x";&nbsp; &nbsp; std::cout << xyzzy << '\n';&nbsp; &nbsp; for (int i = 0; i < std::strlen (xyzzy); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (! std::isdigit (xyzzy[i])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cout << xyzzy[i] << " is not numeric.\n";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; std::string plugh ("3141y59");&nbsp; &nbsp; std::cout << plugh << '\n';&nbsp; &nbsp; for (int i = 0; i < plugh.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (! std::isdigit (plugh[i])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; std::cout << plugh[i] << " is not numeric.\n";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}
随时随地看视频慕课网APP
我要回答