这是我的文件txt的内容:
1 Joey 1992 2 Lisa 1996 3 Hary 1998
我有一个结构:
struct MyStruct
{
int ID;
char *Name;
int Old;
};
我有一个main():
int main ()
{
MyStruct *List;
int Rows, Columns;
ReadFile (List, Rows, Columns, "file.txt");
return 0;
}
现在,我想写一个函数ReadFile来从文件txt获取信息并存储到List中,除了存储行和Colums:
void ReadFile (MyStruct *&List, int &Rows, int &Colums, char const *path)
{
// need help here
}
我知道如何使用ifstream从txt读取整数,但我不知道如何读取子字符串,例如:
“Joey”,“Lisa”和“Hary”
将每个商店存储到char *Name
。
请帮帮我。非常感谢!
答案 0 :(得分:0)
你似乎在做旧学校练习:你使用数组和c-string来存储数据元素,所有麻烦都是手动内存管理。
我将只使用非常基本的语言功能并避免使用任何现代C ++功能
void ReadFile (MyStruct *&List, int &Rows, int &Colums, char const *path)
{
const int maxst=30; // max size of a string
Rows=0; // starting row
ifstream ifs(path);
int id;
while (ifs>>id) {
MyStruct *n=new MyStruct[++Rows]; // Allocate array big enough
for (int i=0; i<Rows-1; i++) // Copy from old array
n[i] = List[i];
if (Rows>1)
delete[] List; // Delete old array
List = n;
List[Rows-1].ID = id; // Fill new element
List[Rows-1].Name = new char[maxst];
ifs.width(maxst); // avoid buffer overflow
ifs>>List[Rows-1].Name; // read into string
ifs>>List[Rows-1].Old;
ifs.ignore(INT_MAX,'\n'); // skip everything else on the line
}
}
这假定在调用函数时List
和Rows
未初始化。请注意,此处未使用Columns
。
请注意,当您不再需要List
时,您必须清理混乱:首先要删除所有Name
,然后删除List
。
如今,您不再使用char*
而是使用string
:
struct MyStruct {
int ID;
string Name;
int Old;
};
你不会使用数组来保存所有项目,而是使用vector
之类的容器:
int main ()
{
vector<MyStruct> List;
ReadFile (List, "file.txt"); // no nead for Rows. It is replaced by List.size()
return 0;
}
然后你会这样读:
void ReadFile (vector<MyStruct>& List, string path)
{
ifstream ifs(path);
MyStruct i;
while (ifs>>i.ID>>i.Name>>i.Old) {
List.push_back(i); // add a new item on list
ifs.ignore(INT_MAX,'\n'); // skip everything else on the line
}
}
不用担心内存管理;不用担心字符串的最大大小。