0

Hi,

I'm trying to add a drop down combo box for user selection in the main window of my application. The program reads USERS.txt, loads each line into a const char*[] and (hopefully) adds them to the combo box. The problem is my program displays Chinese characters instead of the content of the .txt file.

This is my first C++ and first Win32 project, any insight is helpful

const char* users[50];

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;

	hInst = hInstance; 

	hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, 575, 700, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

        HWND hwndSelectUser = CreateWindow (TEXT("COMBOBOX"),
             TEXT("User:"),
             WS_CHILD | WS_VISIBLE | WS_TABSTOP | CBS_DROPDOWN | WS_VSCROLL,
             200, 450, 150, 60,
             hWnd,
             (HMENU) ID_USERCOMBO,
             hInstance,
             NULL);
       int y = LoadUsers();
	
       for(int i = 0; i < y; i ++){			
          SendMessage(hwndSelectUser, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>                   ((LPCTSTR)users[i]));
	}
}

int LoadUsers(){
	string line;
	int counter = 0;
	ifstream userlistfile ("USERS.txt");
	if(userlistfile.is_open()){
		while(userlistfile.good()){
			getline (userlistfile, line);
			users[counter] = line.c_str();
			counter++;
		}
	}
	return counter;

}

-Ben

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Ancient Dragon
0

function LoadUsers() must allocate space for each of the character arrays in the users array. All it is currently doing is using the same std::string over and over again, each time destroying the value of the previous time.

Two fixes:
1. re-declare char* users[100] as vector<string> users.

or
2. replace line 43 >>users[counter] = line.c_str()
with this
users[counter] = strdup(line.c_str());

strdup() does two things:
users[counter] = malloc(length+1);
strcpy(users[counter], line.c_str());

If you opt for option 2 then you need to free() each of those strings when finished with them.

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.