我是 C++ 的新手,我在支票扫描仪的项目中,我正在使用扫描仪随附的 API。这是我的代码:
.h 文件:
#include <iostream>
#include<Windows.h>
#include<vector>
using namespace std;
class Excella
{
public:
vector<char*> getDevicesName();
};
.cpp 文件:
vector<char*> Excella::getDevicesName()
{
DWORD dwResult;
vector<char*> listeDevices;
char pcDevName[128]="";
int i = 6;
// the device's name is stored in the variable 'pcDevName'
while ((dwResult = MTMICRGetDevice(i, (char*)pcDevName)) != MICR_ST_DEVICE_NOT_FOUND) {
dwResult = MTMICRGetDevice(i, (char*)pcDevName);
i++;
listeDevices.push_back((char*) pcDevName);
}
return listeDevices;
}
主要.cpp
vector<char*> liste = excella.getDevicesName();
if (liste.empty()!= true)
{
for (vector<char*>::iterator IterateurListe = liste.begin(); IterateurListe != liste.end(); ++IterateurListe)
{ string str(*IterateurListe);
auto managed = gcnew String(str.c_str());
devices->Items->Add(managed);
}
}
else {
MessageBox::Show("The vector is empty");
}
问题是我可以获得正确的设备编号..我只是有一些奇怪的字符。
谢谢你的帮助。
最佳答案
这并不奇怪。
char pcDevName[128]="";
将在函数结束时超出范围 vector<char*> Excella::getDevicesName()
.因此,您已推送到 vector 的任何指向此的指针都将不再有效。从形式上讲,您的程序的行为是未定义。
使用起来要简单得多 std::vector<std::string>
反而。值得注意的是,这是您必须进行的唯一更改:push_back((char*) pcDevName)
将获取 pcDevName
的值拷贝(这就是 std::string
构造函数的工作原理)。删除不必要的 (char*)
虽然类型转换。
关于c++ - 数组指针的 vector c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34897496/