我需要能够保存一个类对象的向量,我能够做到;但是,我无法弄清楚如何读回数据。我已经尝试了所有我知道如何做的事情以及我在这里看到的一些事情,但这些都没有对我有所帮助。
我创建了一个测试类和main来找出一种读取数据的方法。最新的尝试我能够让第一个对象进入程序,但其余的没有。这是一个测试,看看我是否可以在我将其实现到我的家庭作业之前让它工作,它有多个数据成员
代码:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
class typeA
{
string name; //the name is multiple words
int id;
public:
typeA(string name, int id): name(name), id(id){}
typeA(){}
friend ostream& operator <<(ostream& out, const typeA& a)
{
out << a.name << '\n';
out << a.id << '\n';
return out;
}
friend istream& operator >>(istream& in, typeA& a)
{
getline(in, a.name); // since the name is first and last i have to use getline
in >> a.id;
return in;
}
};
int main()
{
vector<typeA> v;
int id = 1000;
fstream file("testfile.txt", ios::in);
typeA temp;
while(file >> temp)
{
v.push_back(temp);
}
vector<typeA>::iterator iter;
for(iter = v.begin(); iter != v.end(); iter++)
{
cout << *iter;
}
return 0;
}
如果有人能帮助我,我将不胜感激。
答案 0 :(得分:2)
问题出在public View getView(int position, View convertView, ViewGroup parent) {
View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.minute_listview, null);
Typeface afBold = Typeface.createFromAsset(getAssets(), "fonts/AftenScreen-Bold.ttf");
minuteText = (TextView) retval.findViewById(R.id.title);
Button button = (Button) retval.findViewById(R.id.clickbutton);
button.setOnClickListener(mOnButtonClicked);
minuteText.setText(dataObjects[position]);
minuteText.setTypeface(afBold);
//THIS IS WHERE THE BORDER GETS SET
minuteText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundResource(R.drawable.border);
}
});
return retval;
}
。当您阅读operator >>
时,不会消耗以下换行符,因此当您读取下一个对象时,您会读取一个空行作为其名称。解决此问题的一种方法是在阅读id
后致电in.ignore():
id