68 758
Assignments Done
Successfully Done
In January 2019

Answer to Question #75749 in C++ for Kaiba

Question #75749
How to read data from a .txt file into an array of structs..
The file contains data in a table storing Name, Sex, Address and phone number. The amount of lines of data is not known,data reading is terminated by a line containing "end" only.
Expert's answer
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct myStruct
int phoneNumber;
string Address;
string Sex;
string Name;
int main()
ifstream fin("input.txt");
string str;
myStruct* my_Struct = new myStruct[1000];
int counter = 0;
while (true)
getline(fin, str);

if (str == "end")
stringstream ss(str);
string token;

(getline(ss, token, ','));
my_Struct[counter].Name = token;
(getline(ss, token, ','));
my_Struct[counter].Sex = token;
(getline(ss, token, ','));
my_Struct[counter].Address = token;
(getline(ss, token, '\n'));
my_Struct[counter].phoneNumber = stoi(token);
cout << "Finished reading!" << endl;
for (int i = 0; i < counter; i++){
cout << "Name: " << my_Struct[i].Name << endl;
cout << "Sex: "<<my_Struct[i].Sex<< endl;
cout << "Address: "<<my_Struct[i].Address<< endl;
cout << "Number: "<<my_Struct[i].phoneNumber<< endl;

delete[] my_Struct;
return 0;


John, male, Infinite Loop 1, 0077700
Ann, female, Infinite Loop 2, 1077700

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

Privacy policy Terms and Conditions