Cannot convert CHAR to LPWSTR - c++

I encountered a compilation error in Visual Studio 2015, that I am trying to convert char data to LPWSTR. Can I? Or does it work only with string types?
Here is a piece of my code :
⋮
FILE *sortie;
char fichier[256];// <--- HERE s my char table
int main(int argc, char *argv[])
{
//on masque
HWND hwnd = GetForegroundWindow();
ShowWindow(hwnd, SW_HIDE);
int i, lettre, result, lastresult, lastletter, compteur;
GetCurrentDirectory(256, fichier);
strcat(fichier, "\\fichierlog.txt");
Before posting my question I was at:
https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=EN-US&k=k%28C2664%29&rd=true
C++ cannot convert from enum to LPCTSTR
How to Convert char* to LPWSTR in VC++?
I didn't find my case :(

Instead of your current code:
FILE *sortie;
char fichier[256];// <--- HERE s my char table
int main(int argc, char *argv[])
{
//on masque
HWND hwnd = GetForegroundWindow();
ShowWindow(hwnd, SW_HIDE);
int i, lettre, result, lastresult, lastletter, compteur;
GetCurrentDirectory(256, fichier);
strcat(fichier, "\\fichierlog.txt");
do e.g.
auto main() -> int
{
//on masque
HWND hwnd = GetForegroundWindow();
ShowWindow(hwnd, SW_HIDE);
int i, lettre, result, lastresult, lastletter, compteur;
std::wstring fichier( MAX_PATH, L'\0' );// <--- HERE s my char table
const DWORD len = GetCurrentDirectory( fichier.size(), &fichier[0] );
if( len == 0 || len >= fichier.size() ) { throw std::runtime_error( "GetCurrentDirectory failed." ); }
fichier.resize( len );
fichier += L"/fichierlog.txt";
std::ifstream sortie( fichier );
This should fix three issues:
You're compiling as Unicode (probably a Visual Studio project), but the code is for the Windows ANSI API.
You're using a C++ compiler, but the code is low level C.
Too small buffer for maximum path length, and possible buffer overrun for the concatenation.
Note that the ifstream constructor that accepts a wide string is a Microsoft extension. It will however be practically required for Windows C++ compilers by the file system addition to the standard library in C++17.

You are compiling with unicode, so you have to use wchar_t to declare the strings. Instead of strcat use the unicode version which is wcscat.
Also change the strings "\fichierlog.txt" become L"\fichierlog.txt"
FILE *sortie;
//char fichier[256];// <--- HERE s my char table
wchar_t fichier[256];// <--- HERE s my char table
//on masque
HWND hwnd = GetForegroundWindow();
ShowWindow(hwnd, SW_HIDE);
int i, lettre, result, lastresult, lastletter, compteur;
GetCurrentDirectory(256, fichier);
//strcat(fichier, "\\fichierlog.txt");
wcscat(fichier, L"\\fichierlog.txt");

Your Visual Studio project is set to compile using "widechars" as default encoding (aka UNICODE), so all Windows APIs take wchar_t arrays instead of char arrays when handling strings.
Either set your project to use standard charset or specify the ASCII version of GetCurrentDirectory by using GetCurrentDirectoryA instead.
GetCurrentDirectory is actually not a function, but a pre-processor macro that will route you to GetCurrentDirectoryA or GetCurrentDirectoryW depending on what enconding your compiler is set to use.

Related

WinAPI GetWindowText as string

I was wondering if it were possible to take text input from a text box (CreateWindowEx "EDIT") and store it as a string or even better a vector
I need to have a textbox that the user can enter or paste text and when I click a button it will alphabetize the words and count unique words etc...
so far I have it reading it in as characters (i dont know how to make it a string) and alphabetizes the characters
so if I type in: how now brown cow
it will output: bchnnoooorwwww
instead of: brown cow how now
my code under the WM_COMMAND case is
int length;
length = GetWindowTextLength(textbox) + 1;
vector<wchar_t> list(length);
GetWindowText(textbox, &list[0], length);
wstring stxt = &list[0];
wstring str(stxt);
sort(str.begin(), str.end());
SetWindowText(sortedOutput, &str[0]);
This answer may be of use to you in devising a solution. I don't really know of one that is not hacky, but it can be done casting of the constness of c_string() from std::string.
https://stackoverflow.com/a/1986974/128581
A std::string's allocation is not guaranteed to be contiguous under the C++98/03 standard, but C++11 forces it to be. In practice, neither I nor Herb Sutter know of an implementation that does not use contiguous storage.
Notice that the &s[0] thing is always guaranteed to work by the C++11 standard, even in the 0-length string case. It would not be guaranteed if you did str.begin() or &*str.begin(), but for &s[0] the standard defines operator[] as:
Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified
Continuing on, data() is defined as:
Returns: A pointer p such that p + i == &operator for each i in [0,size()].
(notice the square brackets at both ends of the range)
Thus it follows you can do something like this:
int len = GetWindowTextLength(hwnd) + 1;
std::string s;
s.reserve(len);
GetWindowText(hwnd, const_cast<char*>(s.c_str()), len - 1);
Which is pretty ugly. Welcome any more "correct" answers, though.
Regarding when unicode is enabled on your build, you have to use a wstring or equivalent. Testing that out just a moment ago, this works:
std::wstring title;
title.reserve(GetWindowTextLength(m_window_handle) + 1);
GetWindowText(m_window_handle, const_cast<WCHAR *>(title.c_str()), title.capacity());
In general, regarding the windows api its useful to google their all caps typedefs and figure out what they really are.
Regarding splitting strings, std::string isn't particular good at this kind of manipulation. This is where std::stringstream (or wstringstream for unicode) comes in handy. I am fairly certain stringstream is not guaranteed to be contiguous in memory, so you can't really go around writing directly into its buffer.
// Initialize a stringstream so we can extract input using >> operator
std::wstringstream ss;
ss.str(title);
// Make a vector, so we can store our words as we're extracting them
// and so we can use sort later, which works on many stl containers
std::vector<std::wstring> words;
std::wstring word;
// This will evaluate to false and thus end the loop when its done
// reading the string word by word
while(ss >> word)
{
words.push_back(word);
}
Then proceed with your sorting, but on the new vector words.
Your problem is not a winapi problem. While not the only way, you found a solution to transfer a string back and forth to your edit box.
How to turn that string into a list/vector of strings, with words being the elements of that list/vector is in fact an STL problem.
Basically, you are looking for the C++ equivalent of the C# function String.Split().
And there is already a good question and answer for that, here:
Most elegant way to split a string?
So, all you have to do is a sort of round trip:
Get string from TextBox
Convert string to a std::vector<string>, using your split function (see the other question for how to do that).
Sort the vector in the usual way.
Convert the vector back to a string, which is the inverse of your split function (Hint: std::ostringstream).
Set the resulting string as the text of your TextBox.
Depending on your preferences regarding multi character strings and globalization, you might decide to stick to the ASCII versions at first. On windows, you can compile to MBCS or ASCII. The respective string types are then respectively (TCHAR and LPCTSTR or WCHAR and LPCWSTR or CHAR and LPCSTR). All win32 functions come in two flavors, distinguished by a trailing A or W at the end of the function name, respectively.
AFAIK, while there is std::string and std::wstring, there is no standard implementation for std::basic_string<TCHAR>, which would work along with your compile options.
As for the window handling, here some code example (snippets):
In InitInstance(), I created the dialog (IDD_FORMVIEW) with my input edit box, my button and my static output area as a child window of the main application window:
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
HWND hWndChild = CreateDialogW(hInstance, MAKEINTRESOURCE(IDD_FORMVIEW), hWnd, dlgProc);
if (NULL == hWndChild)
{
DWORD lastError = GetLastError();
wchar_t msg[100];
swprintf_s(msg, _countof(msg), L"error code: 0x%0X\n", lastError);
OutputDebugString(msg);
}
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
ShowWindow(hWndChild, SW_SHOW);
UpdateWindow(hWnd);
return TRUE;
}
CreateDialogW() takes as the last parameter a pointer to the dialog handler function, which is called dlgProc() in this example.
This is how that dlgProc() function looks like:
// Message handler for our menu which is a child window of the main window, here.
static INT_PTR CALLBACK dlgProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_In_ WPARAM wParam,
_In_ LPARAM lParam
)
{
BOOL processed = false;
switch (uMsg)
{
case WM_INITDIALOG:
break;
case WM_NOTIFY:
break;
case WM_COMMAND:
{
auto sourceId = LOWORD(wParam);
auto code = HIWORD(wParam);
if (IDC_BUTTON1 == sourceId)
{
if (BN_CLICKED == code)
{
wchar_t text[1024];
GetDlgItemText(hwndDlg, IDC_EDIT1, text, _countof(text));
// TODO: do your string processing here (string -> string)
SetDlgItemText(hwndDlg, IDC_STATIC, text);
processed = TRUE;
}
}
}
break;
default:
break;
}
return processed;
}
I have just mixed a few lines of code to convert wchar_t to wstring to std::string. Here you go!
string GetWindowStringText(HWND hwnd)
{
int len = GetWindowTextLength(hwnd) + 1;
vector<wchar_t> buf(len);
GetWindowText(hwnd, &buf[0], len);
wstring wide = &buf[0];
string s(wide.begin(), wide.end());
return s;
}
This has a vector so you'll need to include it.

Argument of type char is incompatible with parameter type LPWSTR

So I'm learning GUI in c++ to make windows stuff, under my WM_COMMAND case I have an if statement:
//declared globally
char textSaved[20];
HWND TextBox;
//within WM_COMMAND case
if (LOWORD(wParam) == 4)
{
int gwtstat =0;
//char *t = &textSaved[0];
gwtstat = GetWindowText(TextBox, &textSaved[0], 20);
}
and my compiler is telling me that the type "char" is incompatible with the parameter of type "LPWSTR". I'd appreciate it if someone told me what this means and how I could fix it. Also the point of this is to store the content of a text box.
You could try this:
std::vector<wchar_t> textSaved(20);
...
gwtstat = GetWindowText( TextBox, textSaved.data(), textSaved.size() );
testSaved.resize(gwtstat);
std::wstring str(textSaved.begin(), textSaved.end());
In your code you are using char[] to get Window text.
and your application is in UNICODE configuration.
that`s why you are getting error as 'char is incompatible with LPWSTR'.
You can use two method as follows:
METHOD 1 :
About your current code:
As you are using UNICODE Char set for your application.
UNICODE configuration of the application use <wchar.h> file for string handling
you can use following code:
wchar_t textSaved[20];
HWND TextBox;
//within WM_COMMAND case
if (LOWORD(wParam) == 4)
{
int gwtstat =0;
//char *t = &textSaved[0];
gwtstat = GetWindowText(TextBox, &textSaved, 20);
}
Or
Method 2:
If you are using VS2010 or any VS VERSION.
Change project properties to Multibyte so that your project can work with 'Multibyte' char like Japanese char support and you can use char datatype for any operation in the your application.
As MULTIBYTE configuration of the application use the default <string.h> file for string handling
Steps for setting to multibyte
Go to project -> Properties-> configuration Properties->General -> Character Set
and change char set to MULTIBYTE.
and you can use your code as:
//declared globally
char textSaved[20];
HWND TextBox;
//within WM_COMMAND case
if (LOWORD(wParam) == 4)
{
int gwtstat =0;
//char *t = &textSaved[0];
gwtstat = GetWindowText(TextBox, &textSaved, 20);
}
Hope this will help you to understand some thing.

How can I get the current window's title with char * format in C++ on Windows?

I want the write the current window title in console and/or file, and I have trouble with LPWSTR to char * or const char *. My code is:
LPWSTR title = new WCHAR();
HWND handle = GetForegroundWindow();
GetWindowText(handle, title, GetWindowTextLength( handle )+1);
/*Problem is here */
char * CSTitle ???<??? title
std::cout << CSTitle;
FILE *file;
file=fopen("file.txt","a+");
fputs(CSTitle,file);
fclose(file);
You are only allocating enough memory for one character, not the entire string. When GetWindowText is called it copies more characters than there is memory for causing undefined behavior. You can use std::string to make sure there is enough memory available and avoid managing memory yourself.
#include <string>
HWND handle = GetForegroundWindow();
int bufsize = GetWindowTextLength(handle);
std::basic_string<TCHAR> title(bufsize, 0);
GetWindowText(handle, &title[0], bufsize + 1);
You need to allocate enough memory for storing title:
HWND handle = GetForegroundWindow();
int bufsize = GetWindowTextLength(handle) + 1;
LPWSTR title = new WCHAR[bufsize];
GetWindowText(handle, title, bufsize);

Issue with Int to LPWSTR function

I am making a win32 program that is a level editing tool to go with the library I am creating for a 2D tile system.
I want to create dialog box displaying the maps properties when the user selects it from the menu. This means a conversion from int to a wchar_t array. I have created a function that I hoped would do this. However currently it just returns a blank string that the return variable is initialized as. This conversion is necessary to work with the SetDlgItemText() function called by the map properties dialog box.
Here is the function I have currently:
LPWSTR IntToLPWSTR(int value)
{
std::ostringstream convert;
std::string out;
convert << value;
out = convert.str();
const char* in;
in = out.c_str();
LPWSTR ret = L"";
MultiByteToWideChar(CP_ACP, MB_COMPOSITE, in, strlen(in), ret, wcslen(ret));
return ret;
}
It is being called from here:
case WM_INITDIALOG:
if (mapToEdit)
{
SetDlgItemText(hDlg, IDC_TILE_WIDTH_LBL, IntToLPWSTR(mapToEdit->TileWidth()));
SetDlgItemText(hDlg, IDC_TILE_HEIGHT_LBL, L"");
SetDlgItemText(hDlg, IDC_MAP_WIDTH_LBL, L"");
SetDlgItemText(hDlg, IDC_MAP_HEIGHT_LBL, L"");
}
else
{
EndDialog(hDlg, LOWORD(wParam));
MessageBox(hWnd, L"You must create a map first", L"Error", 1);
}
Map to edit is simply a pointer to my own map class that contains the properies I want to display. The bottom three calls to SetDlgItemText() pass L"" as their string, the intention is that they will also use the function when it works.
std::to_wstring is simpler, but to point out the problem in your code, you never created a buffer. LPWSTR ret = L""; makes ret a pointer to an array held in static memory. This array cannot be modified.
Here is one way to fix the code by using std::wstring as the buffer:
std::wstring IntToWstring(int value)
{
std::ostringstream convert;
std::string out;
convert << value;
out = convert.str();
std::wstring ret;
// Find proper length
int length = MultiByteToWideChar(CP_ACP, 0, out.c_str(), out.length(), nullptr, 0);
ret.resize(length);
// Probably should also check for errors (got rid of MB_COMPOSITE flag)
MultiByteToWideChar(CP_ACP, 0, out.c_str(), out.length(), &ret[0], length);
return ret;
}
If you don't want to use std::wstring you could dynamically allocate a buffer LPWSTR ret = new LPWSTR[length];.
EDIT
Also, keep in mind that you could simplify the code to the following:
std::wstring IntToWstring(int value)
{
std::wostringstream convert;
convert << value;
convert.str();
}
You don't need to go to a lot of effort to convert an int into a const wchar_t *. Since C++11, you can take a two-step approach to a std::wstring and a const wchar_t * from there:
SetDlgItemText(hDlg, IDC_TILE_WIDTH_LBL, std::to_wstring(mapToEdit->TileWidth()).c_str());
Sure you could put that into a function to make it one step, but keep in mind that you cannot let the std::wstring be destroyed by the time you use the pointer.

MFC C++ How do I display a const char value in MessageBox?

I hope that the title was good enough to help explain what is needed. After solving this much of my project should be done.
When I did this
char e[1000] = "HELLO";
CString msg;
msg.Format(_T("%s"), e);
MessageBox(msg);
the messagebox just show me random words like "㹙癞鞮㹙癞鞮" instead of the "HELLO" i wanted. How do I solve this problem??
Helps would be appreciated.
Thank You
First of all, are you really using MessageBox API that way. Check the MSDN Documentation.
Now to your question,
char e[1000] = "HELLO";
CString msg;
msg.Format(_T("%S"), e); // Mind the caps "S"
MessageBox( NULL, msg, _T("Hi"), NULL );
I think, you do not even need to Format data here. You can use::
TCHAR e[1000] = _T("HELLO") ;
MessageBox( NULL, e, _T("Hi"), NULL ) ;
This way, if _UNICODE is defined, both TCHAR and MessageBox would get chosen as WCHAR and MessageBoxW and if not defined as char and MessageBoxA.