use printf and strcmp with const char*[] (const char arrays)

Aug 4, 2010 at 1:35pm
here's my problem:

I have this code
1
2
3
4
5
6
7
const char* Name = (const char*) method()->getName(); //this returns a lpcwstr, that's why I cast it

const char* Str[12];
//the following is because original string is a "double char precision"
for(int iter = 0; iter< 22; iter=iter+2)
    Str[iter/2] = Name + iter;


and I want to:
[*] print out the String Str with a printf
[*] compare Str with this string "custom" using strcmp(Str, "custom);

I have a lot of problems since print Str only prints the first char, but I want to print and compare the whole string. please let me know!
Aug 4, 2010 at 3:05pm
I have a lot of problems since print Str only prints the first char

This is most likely because you have const char* Str[12];, change it to char Str[12];.

I assume you know how to use printf and strcmp. If not:
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
Aug 4, 2010 at 4:09pm
Hmm. getName returns a wide string and you are casting to a char*? I'm not sure how that can work. Is lpcwstr a windows typedef?
Aug 4, 2010 at 6:12pm
LPCWSTR is a windows typedef.

http://www.cplusplus.com/forum/articles/16820/ <-- see section 2

Don't try to cast around problem unless you know what the problem is and your cast makes sense. If the compiler is giving you an error saying that the types don't match, casting will not fix the error, it will just silence the compiler (which is a bad thing, because your program will not work as you expect).

The easy solution is to just use the right type:

 
LPCWSTR Name = method()->getName();


there's also no need for that /2 thing you're doing in the for loop. Just copy the data over normally:

1
2
3
char Str[12];
for(int i = 0; i < 12; ++i)
  Str[i] = char( Name[i] );
Aug 5, 2010 at 1:35pm
ok, thank you very much for your answers, they've all been very useful!
Topic archived. No new replies allowed.