I have a txt file includes strings, int, and float. I use a vector to store them. The file can be read and print out. But the vector is not aligned and the double quotes also have not deleted.
These are my codes:
#include<iostream>
#include <string>
#include <vector>
#include <fstream>
#include <stdlib.h>
#include "assignment1.h"
using namespace std;
vector <assignment1*> rsult;
assignment1* parseLine(std::string str)
{
vector<string>store;
string tok = "";
assignment1* retv = nullptr;
for (int i = 0; i < (int)str.size(); i++)
{
char c = str[i];
if (c != ',')
{
tok = tok + c;
}
else
{
store.push_back(tok);
tok = "";
}
}
if (tok != "") { store.push_back(tok); }
retv = new assignment1(store[0], store[1], store[2], store[3], store[4], store[5], store[6]);
//id=store[0]
//name=store[1]
//postcode=store[2]
//city=store[3]
//purchases=store[4]
//returns=store[5]
//cIDs=store[6]
return retv;
}
bool readFile()
{
std::ifstream myFile("Data1.txt");
if (!myFile.is_open())
{
cout << "It failed to open the file" << endl;
return false;
}
std::string str;
int i = 0;
while (std::getline(myFile, str))
{
//cout << "DEBUG -- line " << ++i << " is:" << str << endl;
if (str[0] != '/')
{
assignment1* assignment1 = parseLine(str);
rsult.push_back(assignment1);
}
}
for (assignment1* t : rsult)
{
t->show();
}
return true;
}
void assignment1::show()
{
cout << id << setw(10) << name << setw(10) << postcode << setw(10) << city << setw(10) << purchases << setw(10) << returns << setw(10) << cIDs << endl;
}
The file looks like this:
U2123,Sam Inc,2006, lyons,"21,600.00",13.10,123
A721,Merry Inc,2604, Kingston,"21,600.10",103.00,
U2122,Pippin Inc,2612, reid,"21,600.00",0
The result I print out looks like this:
U2123 Sam Inc 2006 lyons "21 600.00" 13.10
A721 Merry Inc 2604 Kingston "21 600.10" 103.00
U2122Pippin Inc 2612 reid "21 600.00" 0
The result I want is this:
U2123 Sam Inc 2006 lyons 21 600.00 13.10
A721 Merry Inc 2604 Kingston 21 600.10 103.00
U2122 Pippin Inc 2612 reid 21 600.00 0