c++ - Retrieve the name of the computer and saved it in a variable -


this question has answer here:

i'm learning win32 programming c/c++. in process of learning, teacher wanted write simple program can shows name of computer runs on , then, if name of target computer "user", shows warning in output console. written following code, doesn't work.

myfunction code :

tchar * getcomputername() {         bufcharcount = info_buffer_size;         if (!getcomputername(infobuf, &bufcharcount))             printerror(text("getcomputername"));         return (tchar*)infobuf;     } 

calling code :

if (getcomputername() == (tchar*)"user") {             printf("target os detected \n");         } 

how can fix issue?

there several issues code posted. blatant 1 use of tchars. tchar invented, before win9x had unicode support, in attempt keep code source code compatible between win9x , windows nt (the latter uses unicode utf-16le throughout). today, there no reason use tchars @ all. use wchar_t , windows api calls w suffix.

the c-style casts (e.g. return (tchar*)infobuf) error waiting happen. if code doesn't compile without cast in case, means, using incompatible types (char vs. wchar_t).

plus, there's logical error: when using c-style strings (represented through pointers sequence of zero-terminated characters), cannot use operator== compare string contents. compare pointers instead. solution either invoke explicit string comparison (strcmp), or use c++ string instead. latter overloads operator== perform case-sensitive string compare.

a fixed version might this:

#include <windows.h> #include <string> #include <iostream> #include <stdexcept>  std::wstring getcomputername() {     wchar_t buffer[max_computername_length + 1] = {0};     dword cchbuffersize = sizeof(buffer) / sizeof(buffer[0]);     if (!getcomputernamew(buffer, &cchbuffersize))         throw std::runtime_error("getcomputername() failed.");     return std::wstring(&buffer[0]); }  int main() {     const std::wstring compname = getcomputername();     if ( compname == l"user" ) {         std::wcout << l"print message" << std::endl;     } } 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -