class has no member contains

Hi, I'm trying to write a program that generates a random letter and checks if a name entered contains it. The problem is on line 12 it says the class has no member contains.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
#include <random>
#include <string>
using namespace std;
int main()
{
    string name;
    cout << "Please enter your name.";
    cin >> name;
    char cch = 'a' + rand() % 26;
    const auto test = name;
    if (test.contains(cch))
    {
        cout << "Your name contains the random letter we found that is " + cch;
    }


}
std::string has no member function "contains". You need to look at the documentation for std::string to see what functions exist. In this case you could use "find".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <random>
#include <string>
using namespace std;

int main()
{
    default_random_engine rnd(random_device{}());
    uniform_int_distribution<int> dist(0, 25);

    string name;
    cout << "Enter your name: ";
    cin >> name;

    char cch = 'a' + dist(rnd);
    cout << "Letter: " << cch << '\n';

    if (name.find(cch) != name.npos)
    {
        cout << "Your name contains the random letter " << cch << '\n';
    }
}


https://en.cppreference.com/w/cpp/string/basic_string/contains
https://en.cppreference.com/w/cpp/compiler_support/23

This is part of c++23 library, so you need to look at how you are compiling :+)
If you're using C++ random, then the distribution can be from 'a' to 'z' so there's no need to add 'a' later.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <random>
#include <string>
using namespace std;

int main()
{
	default_random_engine rnd(random_device {}());
	uniform_int_distribution<unsigned> dist('a', 'z');
	string name;

	cout << "Enter your name: ";
	getline(cin, name);

	const char cch {static_cast<char>(dist(rnd))};

	cout << "Letter: " << cch << '\n';

	if (name.find(cch) != name.npos)
		cout << "Your name contains the random letter " << cch << '\n';
}


Note that this only works for lc letters entered for name.
Last edited on
Topic archived. No new replies allowed.