开发者

Conversion problem from char * to wchar_t*

开发者 https://www.devze.com 2023-01-23 14:58 出处:网络
The below line works. It prints Success. wchar_t * s1 = (wchar_t *) L\"INSERT INTO OE(sqltext) VALUES(\'this text\')\";

The below line works. It prints Success.

wchar_t * s1 = (wchar_t *) L"INSERT INTO OE(sqltext) VALUES('this text')";

if(WriteToSQL(s1) == 0开发者_如何学JAVA)
  printf( "Success");     //Success
else
  printf( "Failed");     

I need to take user input to create dynamic sql. I need to do what L prefix is doing.

When i take input and do the required conversion, it does not work.

char input[100]; 
char sql[500];  

printf("Enter input string :: "); 
fgets(input,100,stdin); 
for(int i=0;i<100;i++) 
    if(input[i]==10) 
        input[i]=0; 

strcpy(sql,"INSERT INTO OE(sqltext) VALUES('"); 
strcat(sql,input); 
strcat(sql,"')"); 

wchar_t wsql[500];  
MultiByteToWideChar( CP_UTF8, 0, sql, strlen(sql), 
wsql, strlen(sql) + 1 );  


if(WriteToSQL(wsql) == 0)
  printf( "Success");     
else
  printf( "Failed");     // It failed

Long conversassion but finally it did work. Hex memory dump and input from usta was most helpful. Thanks everybody for their time.


You can't just cast a char * to wchar_t * and expect it to work. You must do proper conversion, for example using MultiByteToWideChar function.

And in general, be very careful with type casts, and in particular avoid using C-style casts in C++ programs. This very case is a good example of why: you told the compiler to shut up ((SQLWCHAR *) sql), and in return got a problem at runtime. Use casts only when you are absolutely sure you are doing the right thing, and know better than the compiler. Not surprisingly, such cases are relatively rare...


Why not using wide chars the whole way? Like this:

wchar_t input[100]; 
wchar_t sql[500];  

wprintf(L"Enter input string :: "); 
fgetws(input,100,stdin); 
for(int i=0;i<100;i++) 
    if(input[i]==10) 
        input[i]=0; 

wcscpy(sql,L"INSERT INTO OE(sqltext) VALUES('"); 
wcscat(sql,input); 
wcscat(sql,L"')"); 


if(WriteToSQL(sql) == 0)
  printf( "Success");     
else
  printf( "Failed");     // It failed

Warning:I did not test it, but it should work.


Manjoor, by using _tmain you opted using generic text so be consistent and try to stick to generic-text types throughout your program. That way your code will be cleaner and you won't need to use nasty string conversions like MultiByteToWideChar. If you are in position to change WriteToSQL function signature, pass argument 's' as SQLTCHAR* type. Declare sql and input variables as TCHAR arrays, use string routines from TCHAR.H (e.g. _tprintf instead printf, _T() macro for hardcoded strings...). For each routine you are using, go to its MSDN page and check Generic-text routine mappings to see which one you should use.

Google for Microsoft's support for UNICODE in order to better understand issue you had in the example you provided.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号