转换成c
时间: 2024-01-23 21:08:31 浏览: 28
以下是将 Python 代码转换为 C++ 的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
#include <cstdlib>
#include <cstring>
#include <windows.h>
using namespace std;
int main()
{
// 创建主窗口
HWND hwnd = CreateWindow(
L"STATIC",
L"显示文本文件的内容",
WS_VISIBLE | WS_SYSMENU,
100, 100, 500, 400,
NULL, NULL, NULL, NULL);
// 创建 Listbox 控件
HWND listbox = CreateWindow(
L"LISTBOX",
L"",
WS_CHILD | WS_VISIBLE | WS_BORDER | LBS_HASSTRINGS | LBS_NOTIFY,
10, 10, 460, 340,
hwnd, NULL, NULL, NULL);
// 打开文本文件并将内容逐行添加到 Listbox 控件中
vector<string> lines;
ifstream file("your_text_file.txt");
if (file.is_open())
{
string line;
while (getline(file, line))
{
lines.push_back(line);
}
file.close();
}
else
{
MessageBox(hwnd, L"打开文件失败", L"错误", MB_OK | MB_ICONERROR);
return 1;
}
for (const auto& line : lines)
{
SendMessage(listbox, LB_ADDSTRING, 0, (LPARAM)line.c_str());
}
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
```
说明:
- `CreateWindow()` 函数用于创建窗口和控件。
- `SendMessage(listbox, LB_ADDSTRING, 0, (LPARAM)line.c_str())` 将每行文本内容添加到 Listbox 控件中。
- `GetMessage()` 函数用于获取消息并进行消息处理,保持程序处于运行状态。