[英]How to read file lines and store them? C++
So far I am able to open a txt
file and store them as variables. 到目前为止,我已经能够打开一个
txt
文件并将其存储为变量。
My txt
file looks like this 我的
txt
文件看起来像这样
Tim, 24, Male
I have been able to store them as variables such as name
, age
, gender
我已经能够将它们存储为变量,例如
name
, age
, gender
This is my code 这是我的代码
ifstream inputfiles ("test.txt");
if(!inputfiles.is_open())
{
}
else
{
while(inputfiles >> name >> age >> gender)
{
cout << name << "\n";
cout << age << "\n";
cout << gender << "\n";
}
However, my code doesn't store the values as variables when my txt
file looks like this... 但是,当我的
txt
文件看起来像这样时,我的代码不会将值存储为变量...
Tim
24
Male
How do I modify my code such that it can read my file line by line and store it in its variables? 如何修改代码,使其可以逐行读取文件并将其存储在变量中?
If I am right, You want to store it like: 如果我是对的,您想像这样存储它:
Use a class 使用课程
class data
{
public:
char name[10],gen;
int age;
void getdata()
{
cout<<"Enter Name";
gets(name);
cout<<Enter age";
cin>>age;
cout<<"enter gender";
cin>>gen;
}
void putdata()//use cout statements here
{
//put cout statements
}
};
Now in your main function,use write functon 现在在您的主要功能中,使用write functon
fstream f;
f.open("YourFile.txt",ios::in|ios::out);
data r;
for(i=0;i<10;i++)
{
r.getdata();
f.write((char*)&r,sizeof(r));
}
Remember,always use read function to print the database values if you used write. 请记住,如果使用写操作,则始终使用读取功能来打印数据库值。
f.seekg(0,ios::beg);
while(!f.eof())
{
f.read((char*)&r,sizeof(r));
}
If you want to store the text as it is without conversion...use put function. 如果您想直接存储文本而不进行转换...请使用put函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.