C++ - 读取字符串字符时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18946459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:21:58  来源:igfitidea点击:

-Error reading characters of string

c++winapi

提问by Victor

I have the following block of code:

我有以下代码块:

for( CarsPool::CarRecord &record : recs->GetRecords())
{
  LVITEM item;
  item.mask = LVIF_TEXT;
  item.cchTextMax = 6;

  item.iSubItem = 0;
  item.pszText = (LPSTR)(record.getCarName().c_str()); //breakpoint on this line.
  item.iItem = 0;
  ListView_InsertItem(CarsListView, &item);

  item.iSubItem = 1; 
  item.pszText = TEXT("Available");
  ListView_SetItem(CarsListView, &item);

  item.iSubItem = 2;
  item.pszText = (LPSTR)CarsPool::EncodeCarType(record.getCarType());
  ListView_SetItem(CarsListView, &item);
}

The information from Visual Studio Debugger is here:

Visual Studio Debugger 的信息在这里:

enter image description here

在此处输入图片说明

Why isn't the program able to read the characters from string?

为什么程序不能从字符串中读取字符?

A test has shown me that it works in this way:

一个测试告诉我它是这样工作的:

MessageBox(hWnd, (LPSTR)(record.getCarName().c_str()), "Test", MB_OK);

采纳答案by IInspectable

getCarNamelikely returns a temporary. After the assignment the temporary object is destroyed and the pointer item.pszTextpoints to invalid memory. You must ensure that the string object is valid during the call to ListView_InsertItem.

getCarName可能返回一个临时的。赋值后临时对象被销毁,指针item.pszText指向无效内存。您必须确保字符串对象在调用 期间有效ListView_InsertItem

std::string text(record.getCarName());
item.iSubItem = 0;
item.pszText = const_cast<LPSTR>(text.c_str());
item.iItem = 0;
ListView_InsertItem(CarsListView, &item);

The const_castis an artifact of the fact that the Windows API uses the same structure to set and retrieve information. When invoking ListView_InsertItemthe structure is immutable, however there is no way to reflect that in the language.

const_cast是 Windows API 使用相同结构来设置和检索信息这一事实的产物。当调用ListView_InsertItem结构是不可变的,但是没有办法在语言中反映出来。

回答by paulsm4

It looks like you're trying to use the value of a C++ "string" in a C/Win32 call.

看起来您正在尝试在 C/Win32 调用中使用 C++“字符串”的值。

stdstring.c_str() is the correct way to do it.

stdstring.c_str() 是正确的方法。

... BUT ...

... 但 ...

You should strcpy() the string to a temp variable, then make the Win32 call with the temp variable.

您应该将字符串 strcpy() 转换为临时变量,然后使用临时变量进行 Win32 调用。