sin*_*inθ 5 c++ numbers class function
我正在研究一个用c ++编写的项目(我刚刚开始学习)并且无法理解为什么这个函数不起作用.我正在尝试使用变量first_name编写"Person"类,并使用函数set_first_name来设置名称.Set_first_name需要调用一个函数(下面的函数)来检查名称中是否有任何数字.该函数总是返回false,我想知道为什么?此外,这是检查数字的最佳方式,还是有更好的方法?
bool Person::contains_number(std::string c){ // checks if a string contains a number
if (c.find('0') == std::string::npos || c.find('1') == std::string::npos || c.find('2') == std::string::npos || c.find('3') == std::string::npos
|| c.find('4') == std::string::npos || c.find('5') == std::string::npos || c.find('6') == std::string::npos || c.find('7') == std::string::npos
|| c.find('8') == std::string::npos || c.find('9') == std::string::npos){// checks if it contains number
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*ley 15
将所有内容更改||为&&.
更好的是:
return std::find_if(s.begin(), s.end(), ::isdigit) != s.end();
Run Code Online (Sandbox Code Playgroud)
或者,如果你有:
return std::any_of(s.begin(), s.end(), ::isdigit);
Run Code Online (Sandbox Code Playgroud)
Pet*_*ood 10
C++ 11:
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>
bool has_any_digits(const std::string& s)
{
return std::any_of(s.begin(), s.end(), ::isdigit);
}
int main()
{
std::string query("H311o, W0r1d!");
std::cout << query << ": has digits: "
<< std::boolalpha
<< has_any_digits(query)
<< std::endl;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
输出:
H311o, W0r1d!: has digits: true
它总是返回,false因为你的逻辑是倒退的.您正在使用||带有== npos检查的运算符.如果字符串中缺少任何一个特定数字,则== npos评估为true并且||满意,因此您返回false.您需要使用!= npos检查然后返回,true如果任何检查评估为true:
bool Person::contains_number(const std::string &c)
{
if (c.find('0') != std::string::npos ||
c.find('1') != std::string::npos ||
c.find('2') != std::string::npos ||
c.find('3') != std::string::npos ||
c.find('4') != std::string::npos ||
c.find('5') != std::string::npos ||
c.find('6') != std::string::npos ||
c.find('7') != std::string::npos ||
c.find('8') != std::string::npos ||
c.find('9') != std::string::npos)
{
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
要么:
bool Person::contains_number(const std::string &c)
{
return (
c.find('0') != std::string::npos ||
c.find('1') != std::string::npos ||
c.find('2') != std::string::npos ||
c.find('3') != std::string::npos ||
c.find('4') != std::string::npos ||
c.find('5') != std::string::npos ||
c.find('6') != std::string::npos ||
c.find('7') != std::string::npos ||
c.find('8') != std::string::npos ||
c.find('9') != std::string::npos
);
}
Run Code Online (Sandbox Code Playgroud)
一个更简单的解决方案是使用find_first_of()而不是find():
bool Person::contains_number(const std::string &c)
{
return (c.find_first_of("0123456789") != std::string::npos);
}
Run Code Online (Sandbox Code Playgroud)
这应该做到!
if (std::string::npos != s.find_first_of("0123456789"))
{
std::cout << "digit(s)found!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)