在 Visual C++ 中读取文件
reading from a file in visual c++
我正在使用 C++ 以 clr windows 形式制作一个项目,我在加载表单时从模板(向量)中的文件检索数据时遇到问题。我的表单有一个按钮来保存代码,该代码调用 class 中的保存方法,编码如下。请建议检索文件的代码应该是什么,谢谢 you.here 记录是向量的名称。
int men_database::save(int count)
{ ofstream out;
out.open("MALE.txt",ios::out|ios::binary);
if(!out)
return -1;
else
{for(int i=0;i<count;i++)
{out<<'\n'<<record[i].getid();
out<<'\n'<<record[i].getname();
out<<'\n'<<record[i].getsize();
out<<'\n'<<record[i].getcolor();
out<<'\n'<<record[i].getprice();
out<<'\n'<<record[i].getpic();
out<<'\n'<<record[i].getwatch();
}
out.close();
}//else ends
return 1;}
这是 reading/writing 的一些基本代码。尽管您可能会在别处找到更好的东西。 \n
用作分隔符。每条记录应该有 2 个字段(在你的是 7 个字段)。每个字段必须是单行字符串。 Ps,在你的问题上使用 c++ 标签会得到更多关注。
int main()
{
{
ofstream f("data.txt");
f << "id1" << endl;
f << "name1" << endl;
f << endl;
f << "id2" << endl;
f << "name2" << endl;
f << endl;
}
{
ifstream f("data.txt");
string id;
string name;
while (f)
{
f >> id;
f >> name;
if (!f) break;
cout << "id: " << id << endl;
cout << "name: " << name << endl;
cout << endl;
}
}
return 0;
}
我正在使用 C++ 以 clr windows 形式制作一个项目,我在加载表单时从模板(向量)中的文件检索数据时遇到问题。我的表单有一个按钮来保存代码,该代码调用 class 中的保存方法,编码如下。请建议检索文件的代码应该是什么,谢谢 you.here 记录是向量的名称。
int men_database::save(int count)
{ ofstream out;
out.open("MALE.txt",ios::out|ios::binary);
if(!out)
return -1;
else
{for(int i=0;i<count;i++)
{out<<'\n'<<record[i].getid();
out<<'\n'<<record[i].getname();
out<<'\n'<<record[i].getsize();
out<<'\n'<<record[i].getcolor();
out<<'\n'<<record[i].getprice();
out<<'\n'<<record[i].getpic();
out<<'\n'<<record[i].getwatch();
}
out.close();
}//else ends
return 1;}
这是 reading/writing 的一些基本代码。尽管您可能会在别处找到更好的东西。 \n
用作分隔符。每条记录应该有 2 个字段(在你的是 7 个字段)。每个字段必须是单行字符串。 Ps,在你的问题上使用 c++ 标签会得到更多关注。
int main()
{
{
ofstream f("data.txt");
f << "id1" << endl;
f << "name1" << endl;
f << endl;
f << "id2" << endl;
f << "name2" << endl;
f << endl;
}
{
ifstream f("data.txt");
string id;
string name;
while (f)
{
f >> id;
f >> name;
if (!f) break;
cout << "id: " << id << endl;
cout << "name: " << name << endl;
cout << endl;
}
}
return 0;
}