简体   繁体   中英

pass string to bool function

How can I get tis to work by passing a string to a Boolean function? I need to have the user input a series of strings, and after each entry, the program should give feedback depending upon whether or not the string fit the given criteria. The string should contain the substring of "1101", without any letters. Thanks for all your help

#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 takes a parameter of type char* , but you're trying to pass a std::string . That won't work.

You can either use the c_str method of std::string , to get a const char* pointing to the std::string 's internal char array. This means that you'll have to chance the parameter to const char* .

Or, much better, you can replace stringCompare to take a reference to a std::string :

bool stringCompare(string& y)

and change strlen(str2) to str2.length() . (Or even better, replace the whole loop to simply:

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

)


Also, you don't need to compare the return value == true . Just do:

while(stringCompare(str2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM