【问题标题】:C++ Set Window Text issueC ++设置窗口文本问题
【发布时间】:2021-09-11 16:52:07
【问题描述】:

好的,我有一个包含以下内容的 file.txt:

xzline1\n
xzline2\n

当我运行它时,窗口包含以下内容:

xzline1\nxzline2\n

而不是

xzline1
xzline2

无法识别 \n 换行符,不知道为什么。

我的窗口是这样定义的

        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;
            }

【问题讨论】:

  • 您的文件是否在字面上包含反斜杠 ('\'),后跟一个 'n' 在每行的末尾,或者我的格式化尝试是否掩盖了问题?
  • 是的,每一行最后都包含\n。我实际上在没有 \n 的情况下尝试了它,它只是在一行上显示了所有内容,例如 xzline1xzline2
  • 我在下面写了一个答案。但是,如果您的文本文件中确实有一个“斜线”和一个“n”,那么答案仍然主要适用。您必须将行尾指示符转换为 "\r\n",以便 Windows 将其解释为编辑控件的行尾标记。
  • 这是\n 代码为10 (0x0A) 的单个字符还是“反斜杠-小写-N”?可能是第二个(错误),因为“xzline1\nxzline2\n”中有“\n”。

标签: c++ winapi


【解决方案1】:

经典的 Windows 常用控件需要 DOS 行结尾,\r\n。将所有\n 字符转换为\r\n

也许可以作为一个快速破解来做到这一点:

 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);

或者,很可能您的input.txt 被写为带有\r\n 行结尾的标准Windows 文本文件,而C++ 运行时只是将所有这些\r\n 实例转换为\n 字符。如果是这种情况,您可以将文件作为二进制文件打开,这样就不会发生转换。

替换这个:

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

有了这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多