67 014
Assignments Done
99,4%
Successfully Done
In November 2018

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
{
public:
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")
{
fin.close();
break;
}
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);
counter++;
}
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;
}




Input.txt:

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

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!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions