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;
}
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.
istream & operator >>(istream & input, CustomLong & longi)
{
string inputstring;
input >> inputstring;
vector<long> trans;
for (int i = 0; i<inputstring.length(); ++i)
{
trans.push_back((long)(str.at(i)-'0'));
}
(longi.classVec) = trans; // assign vector to the class variable
return input; //works fine without it
}
I noticed that the method works fine even if we don't return input, is there any problem that can arise if we don't return input? If it doesn't do anything, I'd prefer not to put it, because it uses unnecessary resources.
The method itself may work fine, but if you are chaining inserters it won't.
std::cout << thisCustomLong << std::endl;
Will fail.
Edit: Also returning a value does not "use extra resources" for any practical definition of the term. Avoid micro-optimizing your program (I routinely work on systems than handle over ten million transactions a second (yes I got my decimal point right)) and I wouldn't worry about method like this returning a value.
I assigned myself some homework over the summer, and the project I am 98% finished with has come to a standstill due to this one problem.
I have a class called Mixed. It contains member data for a whole number, a numerator, and a denominator. I need to overload all of the common operators to allow multiplication, addition, comparison and streaming of objects of type Mixed. I have all the operators overloaded except for >> (the extraction operator).
All mixed numbers read in will be of format:
whole numerator/denominator
ex: 1 2/3, 0 7/8, -3 18/5, 0 -1/89
Header: friend istream& operator>> (istream &, Mixed);
CPP file: istream& operator>> (istream &in, Mixed m) {...}
For the assignment, I am limited to the iostream and iomanip libraries. My plan was to read in the values from the stream and assign them to temporary int variables (w, n, d) which I would then use with the Mixed constructor to create object m. Unfortunately, I cannot think of a way to separate the numerator and denominator. They are both ints, but they have a char (/) between them.
I cannot use getline() with its delimiter, because it assigns data to a char array, which I do not believe I can convert to an int without another library.
I cannot use a char array and then segment it for the same reason.
I cannot use a while loop with get() and peek() because, again, I do not think I will be able to convert a char array into an int.
I cannot use a string or c-string and then segment it because that requires external libraries.
Once again, I need to split a value like "22/34" into 22 and 34, using only iostream and iomanip. Is there some fairly obvious method I am overlooking? Is there a way to implicitly convert using pointers?
You could first extract the nominator, then the separating character, and then the denominator.
Example for illustration:
istream& operator>> (istream &in, Mixed &m) {
int num, denom;
char separ;
in >> num;
in.get(separ);
if (separ != '/')
in.setstate(ios::failbit);
in >> denom;
if (in) {
// All extraction worked
m.numerator = num;
m.denominator = denom;
}
return in;
}
Once again, I need to split a value like "22/34" into 22 and 34, using
only iostream and iomanip.
Couldn't you just read in the first integer, use get to get the next character, and then read the second integer? Something like this:
#include <iostream>
int main() {
using std::cin;
using std::cout;
int num;
int den;
while(cin) {
cin >> num;
if (cin.get() != '/') {
// handle error
}
cin >> den;
cout << num << "/" << den << std::endl;
}
return 0;
}
You can then make sure that the character read between the two integers was a '/' and handle appropriately if it isn't.
this is part of a homework assignment. I don't want an answer just help. I have to make a class called MyInt that can store any sized positive integer. I can only use cstring cctype iomanip and iostream libraries. I really don't understand even where to begin on this.
6) Create an overload of the extraction operator >> for reading integers from an input stream. This operator should ignore any leading white space before the number, then read consecutive digits until a non-digit is encountered (this is the same way that >> for a normal int works, so we want to make ours work the same way). This operator should only extract and store the digits in the object. The "first non-digit" encountered after the number may be part of the next input, so should not be extracted. You may assume that the first non-whitespace character in the input will be a digit. i.e. you do not have to error check for entry of an inappropriate type (like a letter) when you have asked for a number.
Example: Suppose the following code is executed, and the input typed is " 12345 7894H".
MyInt x, y;
char ch;
cin >> x >> y >> ch;
The value of x should now be 12345, the value of y should be 7894 and the value of ch should be 'H'.
The last state of my code is as follows:
istream& operator>>(istream& s, MyInt& N){
N.Resize(5);
N.currentSize=1;
char c;
int i = 0;
s >> c;
N.DigitArray[i++] = C2I(c);
N.currentSize++;
c = s.peek();
while(C2I(c) != -1){
s >> c;
if(N.currentSize >= N.maxSize)
N.Resize(N.maxSize + 5);
N.DigitArray[i] = C2I(c);
i++;
N.currentSize++;
}
}
It almost works! Now it grabs the right number but it doesn't end when I hit enter, I have to enter a letter for it to end.
You can create an operator>> overload for your class this way (as a free function, not inside the class):
std::istream& operator>>(std::istream& lhs, MyInt& rhs) {
// read from lhs into rhs
// then return lhs to allow chaining
return lhs;
}
You can use the members peek and read of istream to read in characters, and isspace to test if a character is a space, and isdigit to check if a character is a number (isspace and isdigit are in the <cctype> header).
First of all, your operator>> should be concerned only with extracting the sequence of chars from the stream and knowing when to stop based on your rules for that. Then, it should defer to a constructor of myInt to actually ingest that string. After all, that class will probably want to expose constructors like:
myInt bigone ("123456123451234123121");
for more general-purpose use, right? And, functions should have a single responsibility.
So your general form will be:
istream& operator>> (istream& is, myInt x)
{
string s = extract_digits_from_stream(is);
x = myInt(s);
return is; // chaining
}
Now how do you extract just digits from a stream and stop at a non-digit? Well, the peek function comes to mind, as does unget. I'd look at source code for the extraction operator for regular integers and see what it does.
I'm working on a school project to implement a c++ class for polynomials. Something my class is supposed to do is read polynomials from standard in, or from a file. I thought about overloading >> until I read the following on my favorite c++ reference site:
Notice that the istream extraction operations use whitespaces as
separators, therefore this operation will only extract what can be
considered a word from the stream. To extract entire lines of text,
refer to the string overload of global function getline.
This got me all inspired to overload the global function getline for my polynomial class so that it can read whole lines from a file. There are lots of tutorials and articles describing how to overload the stream extraction operator, but I couldn't find any details about getline. Should I just overload it however I want? From the reference this appears to be how it's done.
In some of the overloaded getline functions I've seen (such as at the bottom of the page linked to), I noticed they return something like "basic_istream". Is it enough that I just return istream? What about for "char_type"? Would char suffice?
Basically I want to know: is this one of those anything goes overloads, or is there some finicky detail I should be worried about?
This is the header I've cooked up:
class Polynomial {
public:
friend istream& getline(istream& is, Polynomial & poly);
friend istream& getline(istream& is, Polynomial & poly, char delim);
};
friend istream& getline(istream& is, Polynomial & poly) {
return getline(is, poly, '\n');
}
friend istream& getline(istream& is, Polynomial & poly, char delim) {
// read enough tokens to make a term
// stop when we get to the delimiter
return is;
}
Thanks!
You should still overload operator >>. Within your operator implementation, you can extract as many 'words' as you need (I'm assuming one per coefficient or so). Don't try to overload getline, thats about getting a line not a Polynomial.