std::string to const char*

I have this portion of a code and I'm receiving this error
error C2664: 'strcmp' : cannot convert parameter 1 from 'std::string' to 'const char *'
So how would I convert std::string to const char * ??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool inDictionary(string word, string dictionary[198])
	
{
	int index = 0;
	bool in_boolean = false;
	while (index < 198 && in_boolean == true)
	{
		in_boolean = strcmp(word, dictionary[index]);
		index++;
		
	}


	return in_boolean;

}


Any and all help is appreciated!! thanks
Use operator== to compare std::strings.
in_boolean = word == dictionary[index];
And for when you have a real need to convert to a const char *, use the string::c_str() method:

http://www.cplusplus.com/reference/string/string/
I addedin_boolean = word == dictionary[index]; but it still doesn't work
but it still doesn't work


Define "doesn't work".

in_boolean = word == dictionary[index]; will work just fine. The only way it could "not work" if is word does not match dictionary[index].
1
2
3
	int index = 0;
	bool in_boolean = false;
	while (index < 198 && in_boolean == true)


Substituting the initial values for index and in_boolean into the the while condition:

while ( 0 < 198 && false == true )

See a problem there?
This is what I have but it still produces the same error when i debug
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool inDictionary(string word, string dictionary[198])

	
{
	int index = 0;
	bool in = false;
	in = word == dictionary[index];
	while (index < 198 && in == true)
	{	
		in = strcmp(word, dictionary[index]);

		index++;
		
	}


	return in;

}
As with the first loop, this new one will never execute as in is false when the loop condition is first evaluated.
Last edited on
I'd do this:
1
2
3
4
5
6
7
bool inDictionary(string word, string dictionary[198])
{
    for (int i = 0; i < 198; ++i)
        if (word == dictionary[i])
            return true;
    return false;
}


Note there is room for optimizing your search (especially if dictionary is in alphabetical order)
closed account (Dy7SLyTq)
why not a map with a look up [edit] function?
Last edited on
Topic archived. No new replies allowed.