I am experimenting with reading input from command line and successfully store them in objects attributes.
Example of input (./(nameOfExecutable) < (sourceText) in the command line)
20 5
1 5
28 5
2 5
20 5
4 5
22 5
88 3
27 5
34 5
I want to read and store them into object attributes.
experimentClass.h
#ifndef EXPERIMENTCLASS_H
#define EXPERIMENTCLASS_H
#pragma once
class experimentClass
{
public:
experimentClass(int x, int y);
~experimentClass();
private:
int age;
int favoriteNumber;
};
#endif
experimentClass.cpp
#include "experimentClass.h"
experimentClass::experimentClass(int x, int y)
{
age = x;
favoriteNumber = y;
}
experimentClass::~experimentClass()
{
}
main.cpp
#include <iostream>
#include "experimentClass.h"
using namespace std;
int main(){
int age;
int favoriteNumber;
std::cin >> age;
std::cin >> favoriteNumber;
experimentClass a(age, favoriteNumber);
}
In this case, I am able to store 20 into a's age, 5 into a's favoriteNumber.
However, I want to do this process until it hits the end of input.
So, in this case, I want to create 10 objects with given input, using iteration, and store these object into an array or something.
How can I read them properly so that I can achieve this?
Simply take the logic you already have and put it inside a loop, eg:
#include <iostream>
#include <vector>
#include "experimentClass.h"
using namespace std;
int main() {
int age;
int favoriteNumber;
vector<experimentClass> vec;
while (cin >> age >> favoriteNumber) {
experimentClass a(age, favoriteNumber);
vec.push_back(a);
}
// use vec as needed...
}
Then you can take this a step further by implementing an operator>> for your class, eg:
#ifndef EXPERIMENTCLASS_H
#define EXPERIMENTCLASS_H
#include <istream>
#pragma once
class experimentClass
{
public:
experimentClass(int x = 0, int y = 0);
friend std::istream& operator>>(std::istream &is, experimentClass &cls);
private:
int age;
int favoriteNumber;
};
std::istream& operator>>(std::istream &is, experimentClass &cls);
#endif
#include "experimentClass.h"
experimentClass::experimentClass(int x, int y)
{
age = x;
favoriteNumber = y;
}
std::istream& operator>>(std::istream &is, experimentClass &cls)
{
return is >> cls.age >> cls.favoriteNumber;
}
#include <iostream>
#include <vector>
#include "experimentClass.h"
using namespace std;
int main() {
experimentClass a;
vector<experimentClass> vec;
while (cin >> a) {
vec.push_back(a);
}
// use vec as needed...
}
You could model the input line with a struct:
struct Record
{
unsigned int m_age;
int m_favorite_number;
};
Then overload the operator>>:
struct Record
{
unsigned int m_age;
int m_favorite_number;
friend std::istream& operator>>(std::istream& input, Record& r);
};
std::istream& operator>>(std::istream& input, Record& r)
{
input >> r.m_age;
input >> r.m_favorite_number;
return input;
}
You could read in the data into a database by using:
std::vector<Record> database;
Record r;
while (std::cin >> r)
{
database.push_back(r);
}
In the above call, you could replace std::cin with a file stream.
You could print or display a record from the database:
std::cout << database[3].m_age << " " << database[3].m_favorite_number << "\n";
Although IMHO, you should overload operator<< to print the record in a default format.
Since you are using nameOfExecutable.exe < source.txt, you can use cin.eof to check if the end of file is reached:
while(true){
int a, b;
std::cin >> a;
if(std::cin.eof()){
break;
}
std::cin >> b;
//Create Class
}
Related
I have given it a few tries based on what I've read on numerous forums and books I have here. More details about this assignment here with more code from it: Click- another question from StackOverflow
What exactly I need to do is create a file with CHotel objects and insert them in this vector m_hoteli.
As to why it isn't working, it is either not reading the string from the file and it's not filling the vector at all.
This is my file:
"Marina" 5 500
"Tulip" 4 400
"BlackSea" 3 300
"SwissBell" 5 600
class CComplex:CHotel
{
protected:
string m_complex;
vector<CHotel> m_hoteli;
public:
CComplex(){};
CComplex(string filename, string nComplex)
{
fstream file("filename.txt", ios::in);
CHotel temp(" ",0,0);
while (file >> temp)
{
m_hoteli.push_back(temp);
}
/* Second try:
m_complex = nComplex;
fstream in;
in.open(filename, ios::in);
string s;
while (getline(in, s))
{
CHotel h1(s);
m_hoteli.push_back(h1);
}
Third try:
m_complex = nComplex;
ifstream iStream(filename);
if (iStream.good())
{
copy(istream_iterator<CHotel>(iStream), istream_iterator<CHotel>(), back_inserter(m_hoteli));
}
}
*/
}
That's the CHotel code:
class CHotel : public CTurist
{
protected:
string hName;
int stars;
int beds;
map<CTurist, unsigned> Turisti;
public:
unsigned Sum = 0;
int br = 0;
CHotel(){};
CHotel(string hName2, int zvezdi, int legla)
{
hName = hName;
stars = zvezdi;
beds = legla;
}
friend istream& operator>>(std::istream& is, CHotel& e)
{
is >> e.hName >> e.stars >> e.beds;;
return is;
}
I just do this in the main: CComplex c1("filename.txt", "Complex1");
You are not using the filename parameter in the CComplex constructor, other than that your code should work.
fstream file(filename, ios::in);
Do you know how to step debug? Here is some info on debugging
Here is your full code, the only change is the filename parameter and the file should now be placed in c:\temp.
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <fstream>
using namespace std;
class CTurist
{
protected:
string tName;
int age;
public:
CTurist() {};
CTurist(string name, int age2)
{
tName = name;
age = age2;
}
bool operator<(const CTurist& e) const
{
return age < e.age;
}
friend ostream& operator<<(ostream& os, const CTurist&& e);
friend ifstream& operator>>(ifstream& is, CTurist&& e);
};
class CHotel : public CTurist
{
protected:
string hName;
int stars;
int beds;
map<CTurist, unsigned> Turisti;
public:
unsigned Sum = 0;
int br = 0;
CHotel() {};
CHotel(string hName2, int zvezdi, int legla)
{
hName = hName;
stars = zvezdi;
beds = legla;
}
friend istream& operator>>(std::istream& is, CHotel& e)
{
is >> e.hName >> e.stars >> e.beds;;
return is;
}
};
class CComplex :CHotel
{
protected:
string m_complex;
vector<CHotel> m_hoteli;
public:
CComplex() {};
CComplex(string filename, string nComplex)
{
fstream file(filename, ios::in);
CHotel temp(" ", 0, 0);
while (file >> temp)
{
m_hoteli.push_back(temp);
}
}
};
int main()
{
CComplex c1("C:\\temp\\file.txt", "Complex1");
system("pause");
return 0;
}
Try putting a breakpoint in main and step through your program with f11 and f10
I'm just a new to C++ And i'm at the beginning...Just want some help...would be appreciate it if somebody can explain where am I wrong with this:
First of all my Time.h code:
#ifndef TIME_H
#define TIME_H
#include<iostream>
using namespace std;
class time {
friend istream &operator>> (istream &, time);
private:
int hour;
int minute;
int second;
public:
time(int = 0, int = 0, int = 0);
void settime(int, int, int);
void sethour(int);
void setminute(int);
void setsecond(int);
};
#endif
And now, Time.cpp:
#include<iostream>
#include"Time.h"
using namespace std;
using std::cout;
using std::cin;
time::time(int h, int m, int s)
{
settime(h, m, s);
}
void time::settime(int hr, int min, int sec)
{
sethour(hr);
setminute(min);
setsecond(sec);
}
void time::sethour(int h)
{
hour = (h >= 0 && h < 24) ? h : 0;
}
void time::setminute(int m)
{
minute = (m >= 0 && m < 60) ? m : 0;
}
void time::setsecond(int s)
{
second = (s >= 0 && s < 60) ? s : 0;
}
istream &operator>> (istream &in, time m)
{
in >> m.sethour >> m.setminute >> m.setsecond;
}
And finally source.cpp:
#include<iostream>
#include"D:\headers\Time.h"
using namespace std;
void main()
{
time t;
cin >> t;
system("pause");
}
But when I compile it, it gives me an error:
1.Error C3867 'time::sethour': non-standard syntax; use '&' to create a pointer to member Project33 D:\headers\Time.cpp
2.Error C2679 binary '>>': no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion) Project33 D:\headers\Time.cpp
Can anybody help me out???
sethour is a member function not a member variable. You need to use a variable.
You can use:
istream &operator>> (istream &in, time m)
{
return (in >> m.hour >> m.minute >> m.second);
}
However, that won't do the calling function any good because you are changing a copy. You need to pass m by reference.
istream &operator>> (istream &in, time& m)
{
return (in >> m.hour >> m.minute >> m.second);
}
Make sure to change the declaration accordingly.
Had the function not been a friend of the class, you could use:
istream &operator>> (istream &in, time& m)
{
// Read the data.
int hour;
int minute;
int second;
in >> m.hour >> m.minute >> m.second;
// Set the member values using function calls.
m.sethour(hour);
m.setminute(minute);
m.setsecond(second);
return in;
}
You're reading into functions here:
in >> m.sethour >> m.setminute >> m.setsecond;
^ ^ ^
That's a simple typo. The bigger problem is that you take the time by value, which prevents any modifications from it to propagating; you probably wanted to take a reference there.
I have a text file that contains a list of students and their marks and looks like this:
Name_of_student 78 4; 98 5; 90 5; 63 3;
...
I have an assignment to create a class that will read and store that data. This is what I've done so far.
group.h
class Subject {
public:
Subject(int mark0, int mark1);
Subject();
int get_m0() { return mark0; }
int get_m1() { return mark1; }
private:
int mark0;
int mark1;
};
class Student {
public:
Student(string name);
Student();
vector<Subject>my_marks;
string get_name() { return name; }
private:
string name;
};
class Reading
{
public:
Reading(vector<Student>, istream& );
istream& read_student();
private:
vector<Student>group;
istream& is;
};
text.cpp
Subject::Subject(int m0, int m1) :
mark0(m0), mark1(m1) {}
Subject::Subject() :
mark0(1), mark1(1) {}
Student::Student(string n0) :
name(n0) {}
Student::Student() :
name("null") {}
Reading::Reading(vector<Student>group0, istream& is0) :
group(group0), is(is0) {}
istream& Reading::read_student()
{
string n;
is >> n;
if (!is) return is;
Student st = Student(n);
for (int i = 0; i < 4; ++i)
{
int m0, m1;
is >> m0 >> m1;
char ch;
is >> ch;
Subject sub = Subject(m0, m1);
st.my_marks.push_back(sub);
}
group.push_back(st);
return is;
}
It compiles, but refuses to read anything.
int main()
{
ifstream ifs("text");
if(!ifs) error("can`t open input file");
vector<Student> group;
Readding r(group, ifs);
r.read_student();
cout << group.size();
}
And what it shows:
0
If anyone has any ideas I'd appreciate it.
In Reading::read_student(), you are filling up the member variable Reading::group. You are not filling up the function variable group in main.
Use:
int main()
{
ifstream ifs("text");
vector<Student> group;
Readding r(group, ifs);
r.read_student();
cout << r.group.size();
// ^^^^^^^^ access the member variable of r.
}
If you want the function variable group to be filled up, Reading needs to store a reference to the input group.
class Reading
{
public:
Reading(vector<Student> & , istream& );
// ^^^^^^ Take a reference as input
istream& read_student();
private:
vector<Student>& group;
// ^^^^^^ store a reference
istream& is;
};
What i have changed:
group.h
class Reading
{
public:
Reading( istream& );
vector<Student>group;
istream& read_student();
private:
istream& is;
};
text.cpp
Reading::Reading(istream& is0) :
is(is0) {}
int main()
{
ifstream ifs("text");
if(!ifs) error("can`t open input file");
Readding r(ifs);
r.read_student();
cout << r.group.size();
}
And now it works all correct!!!
I want to read a data from text file using structure and load it into vector.
so I wrote a following to do this but I failed to compile. I don't know what's wrong.
< what I did >
text file contains data as follows;
835,5,0,0,1,1,8.994,0
(integer array[3], integer,integer,integer,integer,integer, float, Boolean)
2.I declared a structure contains following data types to load data into vector;
struct unfinished
{
int ans[3]; // contains answer
int max;
int st;
int ba;
int outs;
int tri;
float elapsed;
bool fin;
};
3.I wrote a code to read a data as follows;
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct unfinished
{
int ans[3];
int max;
int st;
int ba;
int outs;
int tri;
float elapsed;
bool fin;
};
vector<unfinished> read_rec(istream & is)
{
vector<unfinished> rec;
int ans[3];
int max, st, ba, outs, tri;
float elap;
bool fini;
while (is >> ans[0] >> ans[1] >> ans[2] >> max >> st >> ba >> outs >> tri >> elap >> fini)
{
rec.emplace_back(ans[0], ans[1], ans[2], max, st, ba, outs, tri, elap, fini);
}
return rec;
}
int main(void)
{
ifstream infile("unfin_rec.txt");
auto unfin = read_rec(infile);
vector<unfinished>::const_iterator it;
for (it = unfin.begin(); it != unfin.end(); it += 1)
{
cout << it->ans[0] << it->ans[1] << it->ans[2] << "," << it->max << "," << it->st << "," << it->ba <<","<<it->outs<<","<<it->tri<<","<<it->elapsed<<","<<it->fin<< endl;
}
system("pause");
return 0;
}
I failed to compile this code. error message was: >c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(600): error C2661: 'unfinished::unfinished' : no overloaded function takes 10 arguments
again, I couldn't figure out what this message means. Please help!
thanks,
seihyung
You need to add a constructor which takes 10 arguments and fills in the members of the struct, like so:
struct unfinished
{
unfinished(int a0, int a1, int a2,
int m, int s, int b, int o, int t,
float e, bool b):
max(m), st(s), ba(b), outs(o), tri(t), elap(e), fini(b) {
ans[0]=a0, ans[1]=a1, ans[2]=a2;
}
....
};
So I have a class Coord which is a screen location (x, y) and a class Grid which should be an array of 13 of these Coords, read in from a text file.
The error I'm bumping against is error C2512: 'Coord' : no appropriate default constructor available grid.h 26
Although I have two constructors for the Coord.h, I thought it would use the input stream one? Kinda hacking bits and pieces from other sources here and learning at the same time so please excuse me if I'm overlooking something obvious.
Coord.h
# pragma once
// class for whole screen positions
#include "DarkGDK.h"
#include <istream>
using std::istream;
class Coord
{
float cx, cy;
public:
Coord(float x, float y) : cx(x), cy(y) {} //set components directly
Coord(istream& input); //set from input
float x()
{
return cx;
}
float y()
{
return cy;
}
Coord operator+(const Coord& c);
};
Coord::Coord(istream& input)
{
input >> cx >> cy;
}
Coord Coord::operator+(const Coord& c)
{
return Coord(cx+c.cx, cy+c.cy);
}
Grid.h
# pragma once
// class for the grid array
#include "DarkGDK.h"
#include "Coord.h"
#include <fstream>
#include <iostream>
using namespace std;
const int N = 13;
const char filename[] = "grid.txt";
class Grid
{
Coord gridpos[N];
public:
Grid();
void FillGrid(); //read-in coord values
};
Grid::Grid()
{
FillGrid();
}
void Grid::FillGrid()
{
int i;
ifstream filein(filename, ios::in); //file for reading
for(i=0; !filein.eof(); i++)
{
filein >> gridpos[i].x >> gridpos[i].y; //read in
filein.close();
}
}
Any help is appreciated, thanks.
There are numerous little errors in your code. Here's a version that works with some annotations.
#include <fstream>
#include <iostream>
using namespace std;
const int N = 13;
const char filename[] = "grid.txt";
class Coord
{
float cx, cy;
public:
// Default constructor required to declare array: eg Coord c[23];
Coord() : cx(0), cy(0)
{}
Coord(float x, float y) : cx(x), cy(y)
{}
// You were returning float instead of float& which means you could not update
float& x()
{
return cx;
}
float& y()
{
return cy;
}
Coord Coord::operator+(const Coord& c)
{
return Coord(cx+c.cx, cy+c.cy);
}
friend istream& operator>>(istream& input, Coord& rhs)
{
input >> rhs.cx >> rhs.cy;
return input;
}
};
class Grid
{
Coord gridpos[N];
public:
Grid()
{
FillGrid();
}
void FillGrid()
{
int i;
ifstream filein(filename, ios::in); //file for reading
for(i=0; !filein.eof(); i++)
{
filein >> gridpos[i];
}
// Close the file after you have finished reading from it
filein.close();
}
};
int main()
{
Grid g;
return 0;
}