Good afternoon!
I am attempting to read information from a file using getline() but the information is not outputting correctly. I believe there may be an issue with the way I am using substrings to parse out the data within the text file. Within the code I've created a string that provides an example of how a line looks within the text file. There are 10 other lines similar to this string.
What I've attempted in xcode:
- read the "ClientList.txt" file
- display the parsed out information using substrings
- output a new file "ClientListv2.txt" file
Believe I'm failing to:
- properly use substrings
- properly use arrays
- properly output the information I've gathered
- have the ClientListv2.txt file display any information.
CODE:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int size = 20;
string line;
string name[size], phone_number[size], email[size], street[size], cityState[size];
int i; // variable loop
int clientcount = 0; // loop variable and actual number of records
string example = "George A Harrison 713-555-1234
[email protected] 2503 N Main Street, Baytown, TX ";
cout << "Opening file ClientList.txt : " << endl;
ifstream inputfile;
inputfile.open("ClientList.txt");
if(!inputfile.is_open())
{
cout << "Could not open the file." << endl;
return 1;
}
while(!inputfile) // loop to read file info
{
getline(inputfile, line); // get 1 line of data from the text file
// parse out the data line into our data arrays info
name[clientcount] = line.substr(0, 22);
phone_number[clientcount] = line.substr(23, 12);
email[clientcount] = line.substr(38, 22);
street[clientcount] = line.substr(60, 21);
cityState[clientcount] = line.substr(82);
clientcount++; // increment clientcount
}
inputfile.close(); // done with input file so close the file
for(i = 0; i < clientcount; i++) // display the currect info
{
cout << left << setw(22) << name[i];
cout << setw(14) << phone_number[i];
cout << setw(22) << email[i];
cout << setw(22) << street[i];
cout << cityState[i] << endl;
}
// Modify a phone number and address
phone_number[3] = "555-555-5555";
street[5] = "555 Elm Street,";
// Get input for 2 addition records -- remember to increment clientcount for each additional record
for(i = 0; i < clientcount; i++) // display the currect info
{
cout << left << setw(22) << name[i];
cout << setw(14) << phone_number[i];
cout << setw(22) << email[i];
cout << setw(22) << street[i];
cout << cityState[i] << endl;
}
ofstream outputfile;
outputfile.open("ClientListv2.txt");
if(!outputfile.is_open())
{
cout << "Error opening the output file." << endl;
return 1;
}
{
outputfile << left
<< setw(22) << name[clientcount]
<< setw(14) << phone_number[clientcount]
<< setw(22) << email[clientcount]
<< setw(22) << street[clientcount]
<< cityState[clientcount] << endl;
}
outputfile.close();
return 0;
}