char[] to string OR comparing 2 char[]

Apr 24, 2008 at 4:44pm
Hello,
How do I convert the contents of a char array into a string variable?
For example,
1
2
3
char word[10] = 'hello'; 
string strWord;
strWord = word;




Actually what I want to do is compare the contents of two char arrays but It seams that it will be easier to just convert the contents to string and just compare them using strcmp():

Any assistence will be appreciated.
Apr 24, 2008 at 5:08pm
That should work, if you aren't using single quotes. Use "hello" rather than 'hello'.
Last edited on Apr 24, 2008 at 5:08pm
Apr 24, 2008 at 7:15pm
To convert the char array to a string:
1
2
char word[] = "hello";
string strWord(word);


Actually, you don't need to declare the char array explicitly. It's more common to simply do this:
 
string strWord("hello");


strcmp() is a function from the standard C library (without ++) that compares char arrays, not C++ strings. To compare C++ strings, simply use the '==' operator:
1
2
if (strWord == strOther)
  // they are equal 

Last edited on Apr 24, 2008 at 7:16pm
Apr 24, 2008 at 10:11pm
Thanks rpgfan3233 and ropez, it works:



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


int main()
{
    
 char name1[ 10 ] = "S";
 char name2[ 10 ] = "Sony";
 int result;
 
 
 result = strcmp( name1, name2 );
 
 if ( result == 0 )
    cout << name1 << " is equal to or same as " << name2; 
    else
 if ( result == -1 )
    cout << name1 << " is less than " << name2;
    else
 if ( result == 1 )
    cout << name1 << " is more than " << name2;
    
 
 system ("pause");   
    
}
Apr 25, 2008 at 6:01am
IMHO, I think you should prefer using std::string instead of char[].
Apr 25, 2008 at 11:15pm
string instead of char, ok. Just curious, why? Thanks
Apr 26, 2008 at 1:32am
std::string is more dynamic and useful. char[] is most useful when you need fixed-length strings. Otherwise, std::string is recommended. Of course, it is up to you to decide which one you use. I prefer std::string, but I also do C code as well as C++. For that reason, I find myself using char[] or sometimes char* with malloc()/free() when I need to use strings in C.
Apr 26, 2008 at 11:23pm
Thanks
Topic archived. No new replies allowed.