【发布时间】:2014-01-03 18:42:00
【问题描述】:
bool e_broj(const string &s){
string::const_iterator it = s.begin();
while(it != s.end() && isdigit(*it)){
++it;
}
return !s.empty() && it == s.end();
}
我有这个函数来检查一个字符串是否是一个数字。我在网上找到了这个 sn-p,我想了解它是如何工作的。
// this declares it as the beginning of the string (iterator)
string::const_iterator it = s.begin();
// this checks until the end of the string and
// checks if each character of the iterator is a digit?
while(it != s.end() && isdigit(*it)){
// this line increases the iterator for next
// character after checking the previous character?
++it;
// this line returns true (is number) if the iterator
// came to the end of the string and the string is empty?
return !s.empty() && it == s.end();
【问题讨论】:
-
问题到底是什么?您似乎已经解释了代码...
-
为了清楚起见,您想要解释什么?已经有 cmets 解释了选择的代码行
-
@KerrekSB 问题是帮助我理解代码的作用。我的解释是否正确,还是我的解释有误?我正在尝试了解它是如何工作的。
-
@Huytard 那些 cmets 是我写的,我想知道我是否解释得很好,它是否按照我描述的方式工作,还是我错了?
-
您可能还对
std::find_if感兴趣:return !s.empty() && s.end() == std::find_if(s.begin(), s.end(), [](char c){return !isdigit(c);});