cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : Beginners : How to convert string to *char for strcm...
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Articles
Lounge
Jobs

-

question  How to convert string to *char for strcmp

icemanfan (18)
Here is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool SpellList::searchList (string target)
	{
	bool found;
	
	pPre = NULL;
	pCur = pHead;
	
	while (pCur && strcmp(target, pCur->name) < 0)
		{
		pPre = pCur;
		pCur = pCur->link;
		}
	
	if(pCur && strcmp(target, pCur->name) == 0)
		found = true;
	else
		found = false;
	return found;
	}


It's a simple function and so far the only one giving me trouble, because strcmp needs a *char and not an actual string object. So how can I fix the code so that the first string argument in each of the strcmps doesn't give me a compile error?
|
Duoas (1456)
strcmp(target.c_str(), pCur->name);

You can also store strings in your structures:
strcmp(target.c_str(), pCur->name.c_str());

Hope this helps.
|
bnbertha (404)
You could also use the compare() method from std::string instead of strcmp()
if (pCur && target.compare(pCur->name) == 0)

See http://www.cplusplus.com/reference/string/string/compare.html
|
icemanfan (18)
Duoas: Your method worked for me when I was playing around with the filestream.open() command, but here it didn't work; however, bnbertha's method does work. I wonder why that is. I know my compiler is picky about a few things, such as main having to be an int and returning a value, but I haven't figured them all out yet.
|
Duoas (1456)
If your compiler can't convert a std::string to a const char* using the standard methods ( c_str() or data() ), then it is time to update your compiler to the modern age and get a standard version of the STL.

Alas. :-\
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2008 - All rights reserved - v2.2
Spotted an error? contact us