Hi guys im trying to read this .txt file my problem is that i cant figure out ho
ID: 3765969 • Letter: H
Question
Hi guys im trying to read this .txt file my problem is that i cant figure out how to read the file variable by variable excluding the commas
Donald Duck, 123456789, TRUE, 19, FALSE, 10.95
Mickey Mouse, 258866445, TRUE, 15, FALSE, 9.55
Goofy, 112222445, FALSE, 0, FALSE, 0
Pluto, 558844115, TRUE, 19, TRUE, 11.75
And i have the following code
#pragma once
#include <fstream>
#include "Model.h"
#include <iostream>
using namespace std;
Model::Model()
{
}
Model::~Model()
{
}
void Model::readStudentData()
{
string name;
int IDnumber;
string isWorking;
int hoursWorked;
string isTA;
int payRate;
ifstream file;
file.open("Programming Assignment 4 StudentEmployee Data.txt");
if (file.fail())
{
cout << "file not found!";
}
while (!file.eof())
{
file >> name;
cout << name << endl;
}
}
This prints out everything in the data file including the commas, so my problem is that i want to take each variable seperately and store it into an object of student employee and store it into an array. can anyone help me read the data so that it reads variable by variable not including the commas?
Explanation / Answer
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
void readStudentData() {
string name;
int IDnumber;
string isWorking;
int hoursWorked;
string isTA;
int payRate;
ifstream file;
file.open("D://ravi//Cheg//ProgrammingAssignment4StudentEmployeeData.txt");
if (file.fail()) {
cout << "file not found!";
}
string line;
string word = "";
char delim = ',';
int i;
while (!file.eof()) {
if (!getline(file, line))
break;
istringstream ss(line);
i = 0;
while (ss) {
word = "";
if (!getline(ss, word, ','))
break;
cout << word << " ";
if (i == 0)
name = word;
if (i == 1)
istringstream(word) >> IDnumber;
if (i == 2)
isWorking = word;
if (i == 3)
istringstream(word) >> hoursWorked;
if (i == 4)
isTA = word;
if (i == 5)
istringstream(word) >> payRate;
i++;
}
cout << endl;
cout << "Details: name: " << name << " IDnumber: " << IDnumber<< " isWorking: " << isWorking << " hoursWorked:" << hoursWorked<< " isTA:" << isTA<< " payRate:" <<payRate<<endl;
}
}
int main()
{
readStudentData();
}
--------output---------------
DonaldDuck 123456789 TRUE 19 FALSE 10.95
Details: name: DonaldDuck IDnumber: 123456789 isWorking: TRUE hoursWorked:19 isTA: FALSE payRate:10
Mickey Mouse 258866445 TRUE 15 FALSE 9.55
Details: name: Mickey Mouse IDnumber: 258866445 isWorking: TRUE hoursWorked:15 isTA: FALSE payRate:9
Goofy 112222445 FALSE 0 FALSE 0
Details: name: Goofy IDnumber: 112222445 isWorking: FALSE hoursWorked:0 isTA: FALSE payRate:0
Pluto 558844115 TRUE 19 TRUE 11.75
Details: name: Pluto IDnumber: 558844115 isWorking: TRUE hoursWorked:19 isTA: TRUE payRate:11
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.