Home > Software engineering >  C Set Window Text issue
C Set Window Text issue

Time:09-18

Ok, I have a file.txt which has this contents:

xzline1\n
xzline2\n

When I run it, the window contains this:

xzline1\nxzline2\n

and not

xzline1
xzline2

Not recognizing the \n new line characters, not sure why.

My window is defined like this

        LPCWSTR recordin;
        HWND hEdit;
        hEdit = CreateWindow(TEXT("EDIT"), NULL,
            WS_VISIBLE | WS_CHILD | WS_BORDER | WS_HSCROLL | WS_MAXIMIZE | ES_MULTILINE,
            10, 10, 200, 25,
            hWnd, (HMENU)NULL, NULL, NULL);
       std::ifstream t("c://file.txt");
       std::stringstream buffer;
       buffer << t.rdbuf();
       std::wstring stemp = s2ws(buffer.str());
       recordin = stemp.c_str();
       SetWindowText(hEdit, recordin);

           std::wstring s2ws(const std::string& s)
           {
              int len;
              int slength = (int)s.length()   1;
              len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
              wchar_t* buf = new wchar_t[len];
              MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
              std::wstring r(buf);
              delete[] buf;
              return r;
            }

CodePudding user response:

Classic Windows common controls wants DOS line endings, \r\n. Convert all those \n chars to be \r\n.

Probably can just do this as a quick hack:

 std::wstring stemp = s2ws(buffer.str());

 // quick and dirty string copy with DOS to to unix conversions
 std::wstring stemp2;
 for (char ch : stemp) {
    if (ch == '\n') {
        stemp2  = "\r";
    }
    stemp2  = ch;
 }

 recordin = stemp2.c_str();
 SetWindowText(hEdit, recordin);

Alternatively, it's very likely your input.txt is written out as a standard Windows text file with \r\n line endings and the C runtime is just converting all those \r\n instances to \n chars. If that's the case, you can just open the file as binary so the conversion doesn't happen.

Replace this:

std::ifstream t("c://file.txt");

With this:

std::ifstream t("c://file.txt", std::ios::binary);
  • Related