代码运行,但我不能让cout
工作。请帮助我,我是一个初学者,真的很难得到我的数组的内容输出。
cout << myArray[0].getSquareName();
是从来不是cout
的线。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class cSquare {
public:
string SquareName;
string getSquareName() const;
void setSquareName(string);
friend std::istream & operator >> (std::istream & is, cSquare & s);
};
// set method
void cSquare::setSquareName(string squareName)
{
squareName = SquareName;
}
//square name get method
string cSquare::getSquareName() const
{
return SquareName;
}
ostream & operator << (ostream & os, const cSquare & s)
{
os << s.getSquareName() << ' ';
return os;
}
istream & operator >> (istream & is, cSquare & s)
{
is >> s.SquareName;
return is;
}
int main()
{
string discard;
int i = 0;
const int MAX_SIZE = 26;
ifstream monopoly("monopoly.txt", ios::in);
if (monopoly.is_open())
{
cSquare myArray[MAX_SIZE];
getline(monopoly, discard);
string sname; //string to store what I read in from my file
while (i < MAX_SIZE && monopoly >> sname)
{
myArray[i].setSquareName(sname);//stores the string read in into the array
cout << myArray[0].getSquareName(); //it never cout's this
i++;
}
}
}
您的setSquareName()
方法将对象的SquareName
成员分配给输入参数,这是错误的。你需要做相反的事情,例如:
void cSquare::setSquareName(string sname)
{
//sname = SquareName;
SquareName = sname;
}
同样,这一行:
cout << myArray[0].getSquareName();
应该是这样的:
cout << myArray[i];
有了这两个修改,代码就可以工作了。
演示