This is content of my file txt:
1 Joey 1992 2 Lisa 1996 3 Hary 1998
And I have a struct:
struct MyStruct
{
int ID;
char *Name;
int Old;
};
I have a main () as this:
int main ()
{
MyStruct *List;
int Rows, Columns;
ReadFile (List, Rows, Columns, "file.txt");
return 0;
}
Now, I want to write a function ReadFile to get information from file txt and store into a List, beside store Rows and Colums:
void ReadFile (MyStruct *&List, int &Rows, int &Colums, char const *path)
{
// need help here
}
I know how to use ifstream to read integer from txt, but I don't know how to read substring, such as:
"Joey", "Lisa" and "Hary"
to store each into char *Name
.
Please help me. Thanks so much !
You seem to work on old school exercises: you use arrays and c-string to store data elements, with all the hassle of manual memory management.
I'll use only very basic language features and avoid any modern C++ features
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
}
}
This assumes that List
and Rows
are uninitialized when the function is called. Note that Columns
is not used here.
Note that you'll have to clean the mess when you no longer need the List
: you have first to delete all the Name
and then delete List
.
Nowadays, you'd no longer use char*
but string
:
struct MyStruct {
int ID;
string Name;
int Old;
};
And you wouldn't use an array for keeping all the items, but a container such as vector
:
int main ()
{
vector<MyStruct> List;
ReadFile (List, "file.txt"); // no nead for Rows. It is replaced by List.size()
return 0;
}
And then you'd read it like this:
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
}
}
No worries about memory management; no worries about maximum size of strings.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.