我正在尝试使用从对话框中获取的std :: string创建对象,也进行了几次尝试,但是现在在调试时,我看到已成功获取并传递给构造函数,但是本地参数保持为“”。
这是我的课程标题:
#pragma once
#include <iostream>
#include <istream>
#include <fstream>
#include <string>
class Motorcycle
{
public:
Motorcycle();
Motorcycle(const std::string& nameP, int mileage) : name(nameP), mileage(mileage) {};
friend std::ostream & operator << (std::ostream & out, const Motorcycle & obj)
{
out << obj.name << "\n" << obj.mileage << std::endl;
return out;
};
//friend std::istream & operator >> (std::istream & in, const Motorcycle & obj)
//{
// in >> &obj.name[0] >> obj.mileage;
// return in;
//};
private:
std::string name;
int mileage;
};
cpp仍然是空的(我想也许我应该把构造函数放在那儿,但是结果是一样的?):
#include "stdafx.h"
#include "Motorcycle.h"
#include <string>
Motorcycle::Motorcycle()
{
}
//Motorcycle::Motorcycle(const std::string &nameP, int mileage) : name(nameP), mileage(mileage) {};
这是对话框的过程以及其他功能:
BOOL CALLBACK CreateBikeProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
std::string name = "";
int mileage;
switch (message)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
GetDlgItemTextA(hWnd, IDC_EDIT_NAME, &name[0], 16);
mileage = GetDlgItemInt(hWnd, IDC_EDIT_MILEAGE, NULL, FALSE);
if (ValidateBike(name, mileage))
{
CreateBike(name, mileage);
EndDialog(hWnd, IDOK);
}
break;
case IDCANCEL:
EndDialog(hWnd, IDCANCEL);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
BOOL ValidateBike(std::string& name, int mileage)
{
if (name[0] == ' ' || name.find_first_not_of(' ') != name.npos
|| mileage < 1)
return false;
return true;
}
BOOL CreateBike(std::string& name, int mileage)
{
Motorcycle bike = Motorcycle(name, mileage);
std::ofstream ofs("motorcycles.txt", std::ios::app);
ofs << bike;
ofs.close();
return true;
}
我可以看到CreateBikeProc中的名称已分配并传递给其他函数,但是bike.name为空...
此外,friend std::istream & operator >>
被注释掉,因为它会引起另一个错误...Error 1 error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)
提前感谢...
问题在这里:
GetDlgItemTextA(hWnd, IDC_EDIT_NAME, &name[0], 16);
您无法将值读入这样的字符串中。您需要创建一个缓冲区,然后从缓冲区更新字符串:
char buffer[17]="";
GetDlgItemTextA(hWnd, IDC_EDIT_NAME, &buffer, 16);
name=buffer;