将字符串传递给布尔函数

pass string to bool function

本文关键字:布尔 函数 字符串      更新时间:2023-10-16

如何通过将字符串传递给布尔函数来实现tis?我需要让用户输入一系列字符串,在每次输入后,程序应该根据字符串是否符合给定的标准给出反馈。字符串应包含"1101"的子字符串,不包含任何字母。感谢您的帮助

#include <iostream>
#include <cstring> // for strstr
#include <string>
#include <cctype>
using namespace std;
bool stringCompare(char*y);
string str2;
int main ()
{
    string str1, str2;
    str1= "1101";
    do
    {
    cout << "Please enter your string: " << endl;
    cin >> str2;
    while((stringCompare(str2)) == true)
    {
    if(strstr(str2.c_str(),str1.c_str())) // Primary string search function
    {
    cout << "ACCEPTED  " << endl;
    }
    else
    cout << "NOT ACCEPTED  " << endl;
}
    } while (2 > 1);
    return 0;
}
bool stringCompare(char*y)
{
    for(int a = 0; a < strlen(str2); a++)
    {
    if (!isdigit(str2[a]))
    return false;
    }
    return true;
}

stringCompare接受类型为char*的参数,但您试图传递一个std::string。那行不通。

您可以使用std::stringc_str方法来获得指向std::string的内部char数组的const char*。这意味着您必须将参数设置为const char*

或者,更好的是,您可以将stringCompare替换为引用std::string:

bool stringCompare(string& y)

并且将CCD_ 12改变为CCD_。(或者更好的是,将整个循环简单地替换为:

for(char& ch : str2) // range-based for-loop loops over the entire str2
{
    if (!isdigit(ch))
        return false;
}

)


此外,您不需要比较返回值== true。只需:

while(stringCompare(str2))