【发布时间】:2014-04-15 13:38:17
【问题描述】:
您好,我正在尝试填写我创建的类对象的数组。输入来自文本文件。文本文件包含字符串和数字。我得到了第一组信息,但文件的其余部分不会读入,任何想法都将不胜感激!
class mess
{
private:
string name;
float age, weight, height;
public:
void setname(string a) {name=a;}
void setage(float b){age=b;}
//etc.
string getname(){return name;}
float getage(){return age;}
//etc.
}
ifstream input;
input.open("test.txt");
mess people[2]
string str;
float num;
for(inti=0; i<2; i++)
{
getline(input,str,'\n');
people[i].setname(str);
input >> num;
people[i].setage(num);
input >> num;
people[i].setweight(num);
input >> num;
people[i].setheight(num);
}
for(inti=0; i<2; i++)
{
cout << people[i].getname() << endl;
cout << people[i].getage() << endl;
cout << people[i].getweight() << endl;
cout << people[i].getheight() << endl;
}
test.txt
杰克 17 150.3 5.10 艾米 18 110.4 5.11输出:
杰克 17 150.3 5.10 (空白的) 0 0 0【问题讨论】:
-
for(inti=0; i<2; i++)不会编译,除非您在某处声明了变量inti。这不是真正的代码,是吗? -
在 StackOverflow 中搜索“c++ 读取文件解析”以获取其他示例。
-
@Mile DeSimone :这不是真正的代码,只是我试图做的一个例子。我的意思是 int i = 0。