Pendo826
Pendo826

Reputation: 1002

6 IntelliSense: no suitable conversion function from "std::string" to "int" exists

Hey im validating a string.

string getString(string q)
{
    string input;

    do
    {
        cout << q.c_str() << endl;
        cin >> input;
    } while (!isalpha(input));

    return input;
}

When using while(!isalpha(input)); input gives that error.

Can anyone help me with this?

Upvotes: 0

Views: 5886

Answers (2)

Zoneur
Zoneur

Reputation: 1099

The isalpha function takes an integer as a parameter, but you are passing it a std::string. You could write a function like this to test if your string contains only alphabetical characters:

bool   noDigitInString(std::string str)
{
  for (int i = 0; i < str.size(); i++)
  {
    if (isdigit(str[i]))
      return false;
   }
  return true;
}

Upvotes: 1

Praetorian
Praetorian

Reputation: 109279

The other answer describes what the problem is, but here's a solution that makes use of algorithms from the standard library instead of writing your own (example requires C++11)

bool all_alpha( std::string const& s )
{
  return std::all_of( s.cbegin(), s.cend(), static_cast<int(*)(int)>(std::isalpha) );
}

The above function will return true only if all characters in the string are alphabetic. If you only want to disallow numeric characters, I'd use a slightly different function.

bool any_digit( std::string const& s )
{
  return std::any_of( s.cbegin(), s.cend(), static_cast<int(*)(int)>(std::isdigit) );
}

or

bool no_digits( std::string const& s )
{
  return std::none_of( s.cbegin(), s.cend(), static_cast<int(*)(int)>(std::isdigit) );
}

Use these functions to validate the input that you receive from the user.


If you can't use C++11 features, the functions can be modified to use std::find_if instead, and compare the return value of find_if to s.end() to determine success / failure.

Upvotes: 2

Related Questions