I have file with records separated by comas:
cities.txt:
1,NYC
2,ABQ
...
I would like to iterate over each row: ids and names. I have created the code:
#include <iostream>
#include <string>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, int name)
{
this->id = id;
this->name = name;
}
void load_file()
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
while (!v_file.eof()) {
//...
}
}
v_file.close();
}
}
int main()
{
City array_city[1000];
array_city.load_file();
return 0;
}
Could you tell me how to load all rows to array array_city and iterate over it? I don't know what to place in while block in load_file method. I don't know weather, the method load_file should have void type. Unfortunately I have to do it on arrays.
It's not a good idea to use EOF in a while loop. Read more in Why is iostream::eof inside a loop condition considered wrong?
In c++, vectors should be preferred over arrays. However, your teacher knows something more to suggest using an array here. For that reason I am providing a solution with an array:
Read the file line by line
Extract the id and the string
Assign it to the i-th cell of the array
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, string name) : id(id), name(name)
{
}
void print()
{
cout << "ID = " << id << ", name = " << name << endl;
}
};
void load_file(City* cities, const int n)
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
int number, i = 0;
string str;
char c;
while (v_file >> number >> c >> str && c == ',' && i < n)
{
//cout << number << " " << str << endl;
cities[i++] = {number, str};
}
}
v_file.close();
}
int main()
{
City cities[4]; // assuming there are 4 cities in the file
load_file(cities, 4);
for(unsigned int i = 0; i < 4; ++i)
cities[i].print();
return 0;
}
Same solution with std::vector, if you are interested. =) If you haven't been taught about them, I suggest you skip that part and come back later when you do that in the course.
Use a vector of City. Read the file line by line, and push back into the vector every line you read, by constructing an instance of your class, and you are done!
Example:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class City {
int id;
string name;
public:
City() {}
City(int id, string name) : id(id), name(name)
{
}
void print()
{
cout << "ID = " << id << ", name = " << name << endl;
}
};
void load_file(vector<City>& cities)
{
ifstream v_file("cities.txt");
if (v_file.is_open()) {
int number;
string str;
char c;
while (v_file >> number >> c >> str && c == ',' && i < n)
{
//cout << number << " " << str << endl;
cities.push_back({number, str});
}
}
v_file.close();
}
int main()
{
vector<City> cities;
load_file(cities);
for(unsigned int i = 0; i < cities.size(); ++i)
cities[i].print();
return 0;
}
Input:
Georgioss-MacBook-Pro:~ gsamaras$ cat cities.txt
1,NYC
2,ABQ
3,CCC
4,DDD
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++0x main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
ID = 1, name = NYC
ID = 2, name = ABQ
ID = 3, name = CCC
ID = 4, name = DDD
Related
Basically, the problem is already described in the title: When starting the program first time ( meaning that the new file is created then ), it works perfectly and it doesn't crash, but when trying a second time ( meaning that the file already is there ), it crashes.
Question is: Why does it crash and how do I prevent that from happening?
Here's the code:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
class TStudent
{
public:
string Name, Surname;
int Age;
TStudent(string name, string surname, int age)
{
Name = name;
Surname = surname;
Age = age;
cout <<"\n";
}
string toString() const
{
return Name + " ; " + Surname + " ; " + to_string(Age);
}
int aux1 = sizeof(Name), aux2 = sizeof(Surname);
};
class TRegistru
{
public:
string name, surname;
int age;
vector <TStudent> students;
TRegistru(const TStudent &other)
{
this->name = other.Name;
this->surname = other.Surname;
this->age = other.Age;
students.push_back(other);
}
void adauga(const TStudent& student)
{
students.push_back(student);
}
void salveaza(string file_name)// creating the file and storing the data
{
ofstream file1;
file1.open(file_name, ios::app);
file1.write((char*)&students, sizeof(students));
file1.close();
cout<<"\nFile saved and closed successfully.\n"<<endl;
}
void sterge()
{
students.clear();
}
void incarca(string file_name)// opening the file and reading the data
{
ifstream file2;
file2.open(file_name, ios::in);
if(!file2)
{
cout<<"Error in opening file..";
}
else
{
cout<<"File opened successfully.\n"<<endl;
}
file2.seekg(0);
file2.read((char*)&students, sizeof(students));
}
void afiseaza()//printing the data
{
for(auto student : students)
{
cout << student.Name << endl ;
cout << student.Surname << endl;
cout << student.Age << endl;
cout <<"\n";
}
}
string toString() const
{
string ret{};
for(const auto& student : students)
{
ret += student.toString() + "\n";
}
return ret;
}
};
int main()
{
TStudent student1("Simion", "Neculae", 21);
TStudent student2("Elena", "Oprea", 21);
TRegistru registru(student1);
registru.adauga(student2);
registru.salveaza("data.bin");// creating the file and storing the data
registru.sterge();
registru.incarca("data.bin");// opening the file and reading the data
registru.afiseaza();//printing the data
return 0;
}
After reading a second time your code I realised that the way you try to read and write a vector was plain wrong:
vector <TStudent> students;
...
ifstream file2;
file2.open(file_name, ios::in);
file2.seekg(0);
file2.read((char*)&students, sizeof(students)); // WRONG!!!
A vector does store its data in a contiguous way, but the address of the vector is not the address of the data. The correct way is to serialize each element of the vector to the file and then deserialize each element and push that into the vector.
So I'm unable to create a substring cut using ranges. I am making an airport program where you feed the program a txt.file and it has to divide the lines I get from it into different strings. For instance, I have the following text data:
CL903 LONDON 41000 14.35 08906 //number of flight, destination, price, etc.
UQ5723 SYDNEY 53090 23.20 12986
IC5984 TORONTO 18030 04.45 03260
AM608 TOKYO 41070 18.45 11315
so the first string will be on the lines of this (variables are in Spanish):
numVuelo[n] = M[n].substr(0,5)
this line will work perfectly, but when I move to the next one (from 7 to 14), it tells me that it's out of range, even though It's between the 0 and 31st values of the length of the string.
M[n] gets all of the strings on the text, I'm using Codeblocks and a class style with header and all. I'll copy the code below...
This is my header Vuelo.h:
#ifndef VUELO_H
#define VUELO_H
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
class Vuelo
{
public:
Vuelo(int N);
virtual ~Vuelo();
void setM();
void setNumVuelo(string _numVuelo, int n);
void setDestino(string _destino, int n);
void setPrecio(string _precio, int n);
private:
string M[NUM_FLIGHTS];
string numVuelo[NUM_FLIGHTS];
string destino[NUM_FLIGHTS+1]; //somehow "destino" doesn't work without the +1 but everything else does
float precio[NUM_FLIGHTS];
Then, on another code called Vuelo.cpp I have the following
#include "Vuelo.h"
Vuelo::Vuelo(int N)
{
M[N] = { };
numVuelo[N] = { };
destino[N] = { };
precio[N] = { };
}
Vuelo::~Vuelo()
{
//nope
}
void Vuelo::setM()
{
int c = 1;
string s;
ifstream F ("flights.txt");
if(F.is_open())
{
while (!F.eof())
{
getline(F,s);
M[c] = s;
cout << M[c] << endl;
c++;
}
//sets all values
for(c = 0; c < NUM_FLIGHTS; c++)
{
setNumVuelo(M[c],c);
setDestino(M[c],c);
setPrecio(M[c],c);
}
F.close();
}
else
{
cout << "ERROR document wasn't found" << endl;
}
}
void Vuelo::setNumVuelo(string _numVuelo, int n)
{
numVuelo[n]= _numVuelo.substr(0,5); //this works
cout << numVuelo[n] <<endl;
}
void Vuelo::setDestino(string _destino, int n)
{
destino[n] = _destino.substr(7, 13); //PROBLEM HERE
cout << destino[n] << " " << destino[n].length() << endl;
}
void Vuelo::setPrecio(string _precio, int n)
{
string p = _precio.substr(15,19); //PROBLEM HERE
precio[n] = atof(p.c_str());
cout << precio[n] <<endl;
}
And finally my main looks like this:
#include "Vuelo.h"
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
int main()
{
cout << "Bienvenido, reserva tu vuelo!" << endl;
cout << "-----------------------------------" << endl;
Vuelo* flight = new Vuelo(NUM_FLIGHTS);
flight->setM();
return 0;
}
Thanks :)
I am trying to learn how to use classes and I figured I'd create some sort of supermarket system to aid me with learning. After I have saved all the values from my text file into the temp variables, how do I then use them to create an object? I assume I want one object per item you can "buy"?
If you have any other tips on how to improve my code, please mention them as I just started with C++ a few days ago.
My text file looks like:
42 68 Apples
35 1 Oranges
70 25 Bananas
And my code is below:
// Classes.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
class Products {
private:
int price;
int ID;
int quantity;
public:
void setPrice(int newPrice) {
price = newPrice;
}
void setID(int newID) {
ID = newID;
}
void setQuantity(int newQuantity) {
quantity = newQuantity;
}
int getPrice() {
return price;
}
int getID() {
return ID;
}
int getQuantity() {
return quantity;
}
};
int main()
{
std::string line;
std::string input;
std::string temp;
std::string temp2;
std::string temp3;
int counter = 0;
while (input != "e" && input != "r") {
std::cout << "Do you want to (r)ead the inventory or (e)dit it? (input 'r' or 'e'): ";
getline(std::cin, input);
}
if (input == "r") {
std::ifstream pFile ("products.txt");
if (pFile.is_open()) {
while (getline(pFile, line)) {
std::istringstream iss(line);
iss >> temp >> temp2 >> temp3;
counter++;
}
}
}
return 0;
}
Looking at the text file that you are using as an example and trying to populate a set of classes with the information I'd do something like this:
Text File
42 68 Apples
35 1 Oranges
70 25 Bananas
Looking at the text file you have an int followed by space then another int followed by another space finally followed by a varying size of char[]. We can use this information to create your class or struct and this is how I would create the class based off of the content from the file that is being read in or parsed.
Produce.h
#ifndef PRODUCE_H
#define PRODUCE_H
#include <string>
class Produce {
private:
unsigned price_; // Normally would use float but will use unsigned for simplicity
unsigned quantity_;
std::string name_; // You could use the int as an id as you were using
public:
Produce() {} // Default Constructor
~Produce() {} // Default Destructor
// User Constructor
Produce(const std::string& name, const unsigned& price, const unsigned& qty )
: name_(name), price_(price), quantity_( qty ) {}
// Copy By Const Reference Constructor
Produce(const Produce& other) {
name_ = other.name_;
price_ = other.price_;
quantity_ = other.quantity_;
}
// Assignment Operator
Produce& operator=(const Produce& other) {
name_ = other.name_;
price_ = other.price_;
quantity_ = other.quantity_;
return *this;
}
// Setters & Getters
void setOrChangePrice(const unsigned& priceChange) {
price_ = priceChange;
}
unsigned getPrice() const { return price_; }
void setName(const std::string& name) {
// Already Has A Name? Return!
if (!name_.empty())
return;
}
std::string getName() const { return name_; }
void setOrChangeQuantity(const unsigned& qty) {
quantity_ = qty;
}
unsigned getQuantity() const {
return quantity_;
}
};
#endif // PRODUCE_H
Produce.cpp
#include "Produce.h"
// Normally Constructor(s) & Function Definitions Would Go Here
// Since this is a simple class; I declared & defined them in the header.
Inventory.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include <vector>
#include "Produce.h"
class Inventory {
private:
std::vector<Produce> produce_;
public:
Inventory() {}
~Inventory() {
if (!produce_.empty()) {
produce_.clear();
}
}
std::vector<Produce> getProduceList() const {
return produce_;
}
unsigned getProduceListSize() const {
return static_cast<unsigned>( produce_.size() );
}
void addProduce(const Produce& produce) {
produce_.push_back(produce);
}
Produce getProduce(const std::string& name) const {
for (unsigned n = 0; n < produce_.size(); ++n) {
if (name == produce_[n].getName()) {
return produce_[n];
} else {
return Produce();
}
}
}
unsigned getPrice(const std::string& name) const {
for (unsigned n = 0; n < produce_.size(); ++n) {
if (name == produce_[n].getName()) {
return produce_[n].getPrice();
} else {
return 0;
}
}
}
unsigned getQuantity( const std::string& name ) const {
for (unsigned n = 0; n < produce_.size(); ++n) {
if (name == produce_[n].getName()) {
return produce_[n].getQuantity();
} else {
return 0;
}
}
}
};
#endif // INVENTORY_H
Inventory.cpp
#include "Inventory.h"
Main.cpp
// #include <vector> // Also Included In Inventory.h
// #include <string> // Also Included In Produce.h
#include <iostream>
#include <fstream>
// #include "Produce.h" // Also Included In Inventory.h
#include "Inventory.h"
int main( ) {
// Same As Your Text File
std::string strFilename("ProduceInventory.txt");
std::ifstream fileIn;
// Temps
unsigned price = 0;
unsigned qty = 0;
std::string name;
Inventory inventory;
fileIn.open(strFilename.c_str());
if (!fileIn.is_open()) {
std::cout << "Can not read file\n";
}
while (fileIn >> price >> qty >> name) {
Produce produce(name, price, qty);
inventory.addProduce(produce);
}
if ( fileIn.is_open() ) {
fileIn.close();
}
// Test Our Inventory From File
for (unsigned n = 0; n < inventory.getProduceListSize(); n++) {
std::cout << "Name: " << inventory.getProduceList()[n].getName() << " "
<< "Price: " << inventory.getProduceList()[n].getPrice() << " "
<< "Qty: " << inventory.getProduceList()[n].getQuantity() << "\n";
}
std::cout << std::endl;
// Check To See If Our Search Method Works
std::cout << "Enter a product type by name to get its price and qty on hand.\n";
name.clear(); // reuse
std::cin >> name;
Produce p = inventory.getProduce(name);
if (p.getName().empty()) {
std::cout << "We either do not carry this produce or we are out of stock\n";
} else {
std::cout << "Our price is " << p.getPrice() << " and we have " << p.getQuantity() << " on hand\n";
// Or
std::cout << "Our price is " << inventory.getPrice(name) << " and we have " << inventory.getQuantity(name) << " on hand\n";
}
return 0;
}
Now this is just one of many ways this can be done; but also make sure that your text file is in the appropriate location of the working directory for your IDE or that you specify the correct path along with the filename and extension to be able to open and read from the file in the first place.
Much of this code can be fined even more; but I was showing how to use the std::vector<T> container and some of its functions and how to iterate through them and to retrieve its data. This is a basic way of parsing a simple text file when you know the exact format of the text file and for each and every line you will have the same data types in the same order.
This will not work for every kind of file parsing because it depends on the file's format. For example another file might have different kind of data from one line to the next and might have keywords or tags to give a description of what kind of data is coming next. For that kind of parsing you would have to read the entire line in first into a string stream then you would have to be able to parse that string stream via tokens to extract the data. Some times parsing a file might have multiple lines that belong to a data set and for that you would have to parse by chunks or blobs.
Parsing text files is harder to parse than binary file formats because you have to check each line and character of the text and you also have to be cautious
of character returns, new line characters etc. With binary format you just have to know how many bytes to read in and what type of data it is expected to be. There are many books that are written on just this topic alone on how to parse data from a file. There is no one simple way that fits all.
I am trying to create a program that uses class, arrays, and functions to show information about two students(Name, id#, classes registered). The part I am struggling with is passing arrays to a function. How do I do that?
#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
class Student // Student class declaration.
{
private:
string name;
int id;
string classes;
int arraySize;
public:
void setName(string n)
{
name = n;
}
void setId(int i)
{
id = i;
}
void setClasses(string c, int num)
{
classes = c;
arraySize = num;
}
string getName()
{
return name;
}
int getId()
{
return id;
}
void getClasses()
{
for (int counter=0; counter <arraySize; counter++) {
cout << classes[counter] << endl;
}
}
};
int main()
{
//Student 1
string s1Name = "John Doe";
int s1Id = 51090210;
int const NUMCLASSES1 = 3;
string s1Classes[NUMCLASSES1] = {"C++","Intro to Theatre","Stagecraft"};
//Student 2
string s2Name = "Rick Harambe Sanchez";
int s2Id = 666123420;
int const NUMCLASSES2 = 2;
string s2Classes[NUMCLASSES2] = {"Intro to Rocket Science","Intermediate Acting"};
//
Student info;
info.setName(s1Name);
info.setId(s1Id);
//info.setClasses(s1Classes, NUMCLASSES1);
cout << "Here is Student #1's information:\n";
cout << "Name: " << info.getName() << endl;
cout << "ID: " << info.getId() << endl;
//cout << "Classes: " << info.getClasses() << endl;
info.setName(s2Name);
info.setId(s2Id);
// info.setClasses(s2Classes, NUMCLASSES1);
cout << "\n\nHere is student #2's information:\n";
cout << "Name: " << info.getName() << endl;
cout << "ID: " << info.getId() << endl;
//cout << "Classes: " << info.getClasses() << endl;
return 0;
}
The usual way to pass around variable-length lists in C++ is to use an std::vector. A vector is a single object that you can easily pass to a function, copying (or referencing) its contents. If you are familiar with Java, it's basically an ArrayList. Here is an example:
#include <vector>
#include <string>
using namespace std;
class foo {
private:
vector<string> myStrings;
public:
void setMyStrings(vector<string> vec) {
myStrings = vec;
}
}
//...
foo myObj;
vector<string> list = {"foo","bar","baz"};
myObj.setMyStrings(list);
If don't want to use the standard library though, you can pass an array C-style. This involves passing a pointer to the first element of the array, and the length of the array. Example:
void processStrings(string* arr, int len) {
for (int i = 0; i < len; i++) {
string str = arr[i];
//...
}
}
string array[] = {"foo","bar","baz"};
processStrings(array, 3); // you could also replace 3 with sizeof(array)
Passing raw arrays like this, especially if you wanted to then copy the array into an object, can be painful. Raw arrays in C & C++ are just pointers to the first element of the list. Unlike in languages like Java and JavaScript, they don't keep track of their length, and you can't just assign one array to another. An std::vector encapsulates the concept of a "list of things" and is generally more intuitive to use for that purpose.
Life lesson: use std::vector.
EDIT: See #nathanesau's answer for an example of using constructors to initialize objects more cleanly. (But don't copy-paste, write it up yourself! You'll learn a lot faster that way.)
You can pass array of any_data_type to function like this
void foo(data_type arr[]);
foo(arr); // If you just want to use the value of array
foo(&arr); // If you want to alter the value of array.
Use std::vector. Also, don't add functions you don't need. Here's an example of using std::vector
#include <string>
#include <iostream>
#include <vector>
using std::string;
using std::vector;
class Student // Student class declaration.
{
private:
vector<string> classes;
string name;
int id;
public:
Student (const vector<string> &classesUse, string nameUse, int idUse) :
classes (classesUse),
name (nameUse),
id (idUse)
{
}
void print ()
{
std::cout << "Name: " << name << std::endl;
std::cout << "Id: " << id << std::endl;
std::cout << "Classes: ";
for (int i = 0; i < classes.size (); i++)
{
if (i < classes.size () - 1)
{
std::cout << classes[i] << ", ";
}
else
{
std::cout << classes[i] << std::endl;
}
}
std::cout << std::endl;
}
};
int main()
{
Student John ({"C++","Intro to Theatre","Stagecraft"},
"John",
51090210);
John.print ();
Student Rick ({"Intro to Rocket Science","Intermediate Acting"},
"Rick",
666123420);
Rick.print ();
return 0;
}
Name: John
Id: 51090210
Classes: C++, Intro to Theatre, Stagecraft
Name: Rick
Id: 666123420
Classes: Intro to Rocket Science, Intermediate Acting
In the private variables of class Student, you are storing a string:
String classes;
where as you should be storing an array of strings like:
String classes[MAX_NUM_CLASSES];
then in the set classes function, pass in an array of strings as the first argument, so it should be :
void setClasses(string[] c, int num)
{
classes = c; //not sure if simply setting them equal will work, rather copy entire array using a for loop
arraySize = num;
}
This should point you in the right direction
Also, use std::vector instead of string[], it will be easier.
I am completely lost and have been trying for hours to read from a file named "movies.txt" and storing the info from it into arrays, because it has semicolons. Any help? Thanks.
movies.txt:
The Avengers ; 2012 ; 89 ; 623357910.79
Guardians of the Galaxy ; 2014 ; 96 ; 333130696.46
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
struct Movie {
std::string name;
int year;
int rating;
double earnings;
};
int main()
{
const int MAX_SIZE = 100;
Movie movieList[MAX_SIZE];
std::string line;
int i = 0;
std::ifstream movieFile;
movieFile.open("movies.txt");
while (getline(movieFile, line, ';'))
{
movieFile >> movieList[i].name >> movieList[i].year >> movieList[i].rating >> movieList[i].earnings;
i++;
}
movieFile.close();
std::cout << movieList[0].name << " " << movieList[0].year << " " << movieList[0].rating << " " << movieList[0].earnings << std::endl;
std::cout << movieList[1].name << " " << movieList[1].year << " " << movieList[1].rating << " " << movieList[1].earnings << std::endl;
return 0;
}
What I want is to have:
movieList[0].name = "The Avengers";
movieList[0].year = 2012;
movieList[0].rating = 89;
movieList[0].earnings = 623357910.79;
movieList[1].name = "Guardians of the Galaxy";
movieList[1].year = 2014;
movieList[1].rating = 96;
movieList[1].earnings = 333130696.46;
I amended your code.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
struct Movie {
std::string name;
int year;
int rating;
double earnings;
};
std::vector<std::string>
split(const std::string &s, char delim = ',')
{
std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
int main()
{
std::vector<Movie> movieList;
std::string line;
std::ifstream movieFile;
movieFile.open("movies.txt");
while (getline(movieFile, line))
{
std::vector<std::string> columns = split(line,';');
Movie movie;
movie.name = columns[0];
movie.year = std::stoi(columns[1]);
movie.rating = std::stoi(columns[2]);
movie.earnings = std::stof(columns[3]);
movieList.push_back(movie);
}
movieFile.close();
for (const Movie & m: movieList)
{
std::cout << m.name << " " << m.year << " " << m.rating << " " << m.earnings << std::endl;
}
return 0;
}
Basicly, I added a split function that splits the lines using ';'. Also I use vector to store the movies rather than hard coded array of movies. Much better this way.
P.S. Second version without vectors
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
struct Movie {
std::string name;
int year;
int rating;
double earnings;
};
void split(const std::string &s, char delim, std::string elems[])
{
std::stringstream ss(s);
std::string item;
int i = 0;
while (std::getline(ss, item, delim))
{
elems[i++] = item;
}
}
int main()
{
//std::vector<Movie> movieList;
const int MAX_SIZE = 100;
Movie movieList[MAX_SIZE];
int movieNo = 0;
std::string line;
std::ifstream movieFile;
movieFile.open("/home/marcin/testing/movies.txt");
std::string columns[4];
while (getline(movieFile, line))
{
split(line,';', columns);
movieList[movieNo].name = columns[0];
movieList[movieNo].year = std::stoi(columns[1]);
movieList[movieNo].rating = std::stoi(columns[2]);
movieList[movieNo].earnings = std::stof(columns[3]);
++movieNo;
}
movieFile.close();
for (int i =0; i < movieNo; ++i) {
std::cout << movieList[i].name
<< " "
<< movieList[i].year
<< " "
<< movieList[i].rating
<< " "
<< movieList[i].earnings
<< std::endl;
}
return 0;
}
Use getline(my_movieFile, movie_name, ';') to get the name of the movie up to the ;.
You'll need to figure out how to remove the trailing whitespace from the name if necessary.. you can search for examples.
Read the rest of the line using getline(movieFile, line)
Use std::replace to replace all ; with a space in line
Put line into a std::stringstream.
Then extract the remaining fields from the stringstream using the >> operators.
Put this in loop do { ... } while (movieFile);
Also, don't hardcode an arbitrary number of movies. Use a std::vector<Movie> and push_back to add new ones.
I think you want to break your line into tokens using something like std::strtok. Check out the reference here. The example given on that page uses a blank as a separator, you would use a semicolon.