In: Computer Science
C++ Parse text (with delimiter) read from file.
If a Text file has input formatted such as: "name,23" on every line where a comma is the delimiter, how would I separate the string "name" and integer "23" and set them to separate variables for every input of the text file? I am trying to set a name and age to an object and insert it into a vector.
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Student{
public:
string name;
int age;
};
int main() {
vector <Student>studentVector;
Student s;
string student_name;
int student_age;
ifstream myFile("file.txt");
while(myFile>> student_name >>
student_age){
//s.name is assigning
the entire line of unparsed text
s.name =
student_name;
///age is not read because input string from file is not parsed
s.age = student_age;
studentVector.push_back(s);
}
return 0;
}
working code :
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class Student{
public:
string name;
int age;
};
int main() {
vector <Student>studentVector;
Student s;
string student_details;
ifstream myFile("file.txt");
while(myFile>> student_details){
int index_of_comma = student_details.find(','); // finding the
index of comma(',')
s.name = student_details.substr(0,index_of_comma);// get the string
from 0 to index_of_comma and store ot to s.name
s.age =
stoi(student_details.substr(index_of_comma+1,student_details.size()));
// form index_of_comma+1 to the last stroe it in s.age
// stoi is used to convert the string of number into integer
cout<<"student name is :"<<s.name<<"\nstudent age
is :" <<s.age<<endl; // printing
values
studentVector.push_back(s); // inserting details of
student into vector
}
return 0;
}
if any doubt, comment below