68 462
Assignments Done
98,6%
Successfully Done
In December 2018

Answer to Question #75750 in C++ for Kaiba

Question #75750
The person.txt 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. Declare a struct "Person" to store the information on each person and write a function, readPersoninfo, which accepts a one-dimensional array of Person structs as a parameter and reads the data from person.txt and stores it in the array. The function should return the amount of persons that was read from the file.
Expert's answer
The specific algorithm for reading the data will depend on the format of the input file.
Suppose that the file "person.txt" has csv format, i.e. all fields are separated by commas and there are no spaces between the data and commas:

person.txt
John Rich,M,Triana 188 Huntsville 35806 AL,999999999
end

Then you can write this code:

#include <fstream>
#include <sstream>
#include <string>

using namespace std;

struct Person
{
string Name;
string Sex;
string Address;
string Phone;
};

const int MAX_PERSON = 100; // array size
const string FILENAME = "person.txt"; // filename
const string END = "end"; // end of data
const char FIELD_SEPARATOR = ',';

int ReadPersonInfo(Person person[MAX_PERSON])
{
ifstream in(FILENAME); // create input file stream

if (!in) // failed creating
{
return 0;
}

string line; // line buffer
int count = 0; // line counter

// Read input stream line by line
// until read "end" line
while (getline(in, line) && line != END)
{
// Create string stream from line
// (it is more convenient to work with stream than with a string)
stringstream str(line);

// Read Name from string stream up to FIELD_SEPARATOR
getline(str, person[count].Name, FIELD_SEPARATOR);
// Read Sex from string stream up to FIELD_SEPARATOR
getline(str, person[count].Sex, FIELD_SEPARATOR);
// Read Address from string stream up to FIELD_SEPARATOR
getline(str, person[count].Address, FIELD_SEPARATOR);
// Read Phone from string stream up to end of stream
getline(str, person[count].Phone);

++count; // increase line counter

if (count == MAX_PERSON) // if reached max array size
return count;
}

// return line count
return count;
}

int main()
{
// Create array of Person
Person person[MAX_PERSON];

// Read person info
int count = ReadPersonInfo(person);

return 0;
}


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