I have a file called grades.txt with some lines of text and integers on it that i want to read into an already defined class ive created called Assignment.
int main()
{
ifstream input_file("grades.txt");
Assignment assignment;
input_file >> assignment;
return 0;
}
Above is my main function that will read input_file into the created class assignment.
friend istream& operator >> (istream& is, Assignment& assignment)
{ // function to read in data to class variables
string line;
getline(*****, line);
// to be able to operate on strings
istringstream iss(line);
// set values read in from input file.
iss >> assignment.Assignment_type;
iss >> assignment.Date;
iss >> assignment.Max_score;
iss >> assignment.Actual_score;
// sometimes Assignment Name will have spaces, have to use getline()
getline(is, assignment.Assignment_name);
return is;
}
Heres the class function that will overload the >> operator to read into each of the variables in assignment. the group of stars is what im having problems with, i dont know what to pass to it. I've tried ifstream and ofstream thinking it was that easy but they return the same error code
P01.cpp:34:21: error: expected primary-expression before ‘,’ token
I guess, you defined these operator >> inside the class Assignment. Only declare it as friend, but put the definition somewhere out: it is not a member of Assignment. The error is telling you that Operator >> take only one argument when defined as a member (the right operand, becouse the link is this).
Als "namespace" or global function it accept two arguments: link and right.
Related
I'm having a trouble when I use while(cin) with struct. Would someone please make me clear about this problem? I don't know whether this kind of post was asked or not. If it was please forgive me and my bad english as well.
struct ThiSinh{
string m_HT;
float m_H;
};
I overload operator >> for it
bool operator >> (istream& is, ThiSinh &ts){
getline(is, ts.m_HT);
is >> ts.m_H;
is.ignore();
return ???;
}
Because while (cin >> ThiSinh) require a bool type, so I dont know what number or data it should return. And how to break the while loop when I press ctrl + Z.
I have also tried
while(cin){
ThiSinh ts;
cin >> ts;
}
and it worked but I dont want to get that false data. So someone please helps me out. Thanks in advance.
Your operator >> returns a bool, which is extremely unusual for a stream extraction operator, and renders it unusuable in most streaming contexts. Such operators are expected to return a reference to the stream on which they operate:
istream& operator >> (istream& is, ThiSinh &ts){
getline(is, ts.m_HT);
is >> ts.m_H;
is.ignore();
return is;
}
This is how multiple exrtactions actually work:
std::cin >> a >> b >> c;
Effectively, this first does auto &tmp = operator>>(std::cin, a), and then calls operator>>(tmp, b), and so on.
The reason why streams (and by extension, stream extraction operations) can be used in conditionals is that std::istream (and std::ostream) defines a conversion to bool (which returns true iff the stream is in error-free state); that conversion is then invoked by the conditional.
In other words, this:
while (std::cin >> ts)
effectively becomes this:
while (static_cast<bool>(operator>>(std::cin, ts)))
and the cast is possible because operator>> returns std::istream& and std::istream defines a conversion to bool.
I'm trying to get inputs from a file by overloading the istream operator. For that, I declared it as friend of a class. Then, I take as input that same class like this:
file >> *(class pointer);
When I'm trying to debug the part of my code that need this to work, it goes as expected into this:
istream& operator>> (istream& in, MYCLASS& n)
{
string buffer;
while (!in.eof()) { // input is a file
in >> buffer;
// do stuff
}
return in;
}
The problem is that the buffer stays empty ("") and does not take what it's suppose to be taking from the file. Normally, the format of the file should not be a problem since I'm using a similar method elsewhere in my code without a problem, but here it is in case:
* Name Age
* Name Age
* Name Age
...
What should I put inside my istream overload function so i get inputs as intended?
This...
while (!in.eof()) {
...is broken. You should attempt to read and parse data into your variables, then check for failure/eof. Do not assume that you'll necessarily be at the end of file after reading the last MYCLASS. Instead:
string name;
int age;
while (in >> name >> age)
...do stuff...
If you've really got some kind of leading dot on each line, add a char and read into it too:
char dot;
string name;
int age;
while (in >> dot && dot == '.' && in >> name >> age)
...do stuff...
More generally, it's not a very scalable model to assume the rest of the input stream will contain one MYCLASS object. You could instead have a delimiter (e.g. when the first word on a line is not a name, but <END>), that terminates the loop.
Book.h:
#ifndef BOOKDATE
#define BOOKDATE
#include <iostream>
#include <string>
class Book{
friend std::istream& operator>>(std::istream&, Book&);
private:
std::string title, author;
int number;
};
std::istream& operator>>(std::istream&, Book&);
#endif // BOOKDATE
Book.cpp:
#include "BookDate.h"
using namespace std;
istream& operator>>(istream& is, Book& rhs){
getline(is, rhs.title);
getline(is, rhs.author);
is >> rhs.number;
if(!is)
rhs = Book();
return is;
}
I was wondering how exactly I should approach creating the input operator for the Book class. The title and author will be more than one word, so it fits that I need to use getline to receive that data. The issue then with getline is that it may pick up any '\n' left in the stream since cin was last used. For instance;
int x;
cin >> x; //newline is not extracted and left behind
Book a;
cin >> a; //"title" is automatically made empty!
I could instead use cin.ignore(256, '\n') but whose responsibility, the user's or class author's, is it to use this? Does the user use .ignore before he inputs a Book object or does the class author put .ignore at the beginning of the input operation?
It seems that in the former case the user would have to understand an .ignore method is needed but in doing so has to understand the implementation of the Book's input operator, which is not desirable. In the latter case, putting .ignore in the operator means my operator may not adapt to certain circumstances, since it always expects to encounter a newline before processing. For instance reading from an input file with data such as:
book1
author1
1
book2
author2
2
Means book1 gets ignored by cin.ignore(256,'\n').
To make your operator>> behave more like the operators for the built in types, you can use the ws manipulator to skip whitespace before you read your input.
Just use
is >> ws;
at the beginning of your input operator, and the stream will be positioned at the first non-whitespace character after the current position.
To overload the extraction operator properly you can change your input format to be a sequence of three variables that you want to populate, namely:
(title, author, number)
and modify your operator>> to:
istream& operator>>(istream& is, Book& rhs){
// just a suggestion: it is better if there is no input to do nothing
if(!is) return is;
string title, author;
int number;
char par1, comma, par2;
cin >> skipws >> par1 >> title >> comma >> author>> comma >> number >> par2;
if (par1 != '(' || comma != ',' || par1 != ')'){
// set failbit to indicate invalid input format
is.clear(ios_base::failbit);
}
rhs(title, author, number);
return is;
}
put is.ignore(); before getline(is, rhs.title);
I am trying to finish my lab, however I don't know how to allocate memory to a string. So I keep getting the error
warning: ‘_name’ is used uninitialized in this function [-Wuninitialized]
I don't also understand if my getline line is correct.
std::istream& operator>>(std::istream& is, Grade& RO){
int _mark;
char* _name;
std::cout<<"Subject name: ";
is.ignore();
is.getline(_name, (strlen(_name) + 1));
std::cout<<"Mark :";
is>> _mark;
RO=Grade(_name, _mark);
return is;
}
Ok #Jessica, (to general question and few info) I guess,
Grade is a class with two data members: int mark and string name. And you want to overload the insertion operator >> to populate these values.
(I recommend you leave all the cout expression outside this function). Here is one possible implementation:
istream& operator>> (istream& is, Grade& RO){
// declare local variables to insert the input values
int mark;
string name;
// extract values from input stream
is >> mark >> name;
// assuming you have member functions that set values for the object RO
RO.set_mark(mark);
RO.set_name(name);
return is;
}
So I'm failing a simple input test for one of assignment questions. I'm to parse two integers separated by a white space. The two integers are used in the private members num and denom of the Rationalnumber type I have defined as a class. Is there something obviously unconventional I am using in or missing from this code? This code works for all my tests.
std::istream &operator>>( std::istream &is, Rationalnumber &r ) {
Rationalnumber::in++; // increment counter
// get the num
string n;
getline(cin,n,' ');
stringstream ssnum(n);
ssnum >> r.num;
// get the denom
string d;
getline(cin,d,'\n');
stringstream ssdenom(d);
ssdenom >> r.denom;
return is;
}
Your code fails in, at least, two obvious ways:
If a different whitespace than space is used, e.g., '\t', it isn't recognized by your code.
The input operator doesn't indicate failure when it is given invalid inputs, e.g., when the input is "a b" rather than numbers.
Conventionally, when input fails, the valuevread remains unchanged. This is also not true for your implementation. To fix things up the code can actually be simplified and made a lot fadter in the process. As this is clearly a homework assignment I don't think it is appropriate to provide the code, though.
This code passes the test!:
std::istream &operator>>( std::istream &is, Rationalnumber &r ) {
Rationalnumber::in++; // increment counter
int in;
is >> in;
r.numerator(in);
is >> in;
r.denominator(in);
return is;
}