I am trying to learn c++ and I got struck while using cin in my code
int input;
vec.push_back(cin>>input);
or
int input;
sum+=cin>>input
can anyone please guide me on this?
The reason why it doesn't works is that you can't assign an istream& to an integer.
To put it simply, operators in c++ works like functions. They get a parameter, which stands of the right side and give you a return value, which stands on the left side of the operator and represents the expression.
The Operator ">>" returns an istream reference. You want to assign this istream reference to an integer and this isn't possible.
The overloaded operator to get an integer is
std::istream& operator>>(int& val)
This means that the value you want to assign with this operator must be the parameter.
int input;
std::cin >> input;
sum += input;
You can have a look here to see the documentation of operator >> in istream.
And you can have another look here to see how overloading in c++ works.
And there are many other tutorials to this topic.
Google is your friend ;)
Related
Like I encountered this doubt while learning dynamic memory allocation in C++, and just can't focus anymore on learning it now. :(
int n;
cout << "Enter array size: ";
cin >> n;
int *p = new int[n];
So everything is fine till now, I just allocated n blocks of int memory in heap area
Now, while taking the input using a for loop, I had this doubt while I tried to write p[i] as *(p+i)
for (int i = 0; i < n; i++)
{
// cin >> p[i]; // This is correct
// cin >> *(p+i); // This is correct
cin >> (p + i); // same as cin >> &p[i], right? Now, this gives me error since I didn't deference
// it and now I'm confused as to why we need to deference it? *(p+i) tells which
// block the value is to be stored in, but doesn't (p+i) also give us the same
// address? The input value should still have been stored in the respective memory
// block, right? But it doesn't and I can't visualize it why?
// Also, now I'm even confused as to why writing cin >> n works and writing cin >> &n doesn't??
}
I was simply expecting that my value should still be accepted into the respective array element, but it didn't, rather it gave me a very very wrong error, which I'm unable to understand.
I tried looking for answers, but still unclear with the concept visualization and clarity. All I've known so far is that cin is an object of istream class, >> operator while used with cin is kind of like a function call, and the variable name which we write after the >> operator is "passed by reference" or something like that, which might seem like that is why maybe we don't give address as reference variable already has it by default, but I'm not sure and still in doubt.
Please someone explain it in proper sequence and with proper example. I'll be grateful.
Type of *(p + i) is int and type of (p + i) is int*. With the first one you are reading an integer, so that is clear.
Why doesn't cin >> (p + i) read int? When a function takes parameter by reference, the parameter must be the same exact type. You are giving it int*, so it will try to read int*.
How would we read a pointer? I guess we could read an integer and assign it to the pointer variable. We are currently reading to the temporary value p + i. operator>> needs a reference, which it cannot get for a temporary value, which is why you get a compile error.
Let us skip this problem by using another variable:
int* pi = p + i;
cin >> pi;
This still does not compile, because there is an overload for reading void*, but not int*. In C++, you cannot automatically convert between two pointer types. If you want to read int*, you can do that, but you have to write an overload for operator>>.
the variable name which we write after the >> operator is "passed by reference"
This is exactly the point. One of the main goals of the C language was to build a rather simple compiler able to provide efficient code. As a result, it tried to remain as explicit as possible and only allowed to pass parameters to functions as values. If you want to modify something from a function you just pass a pointer to it.
C++ language is aimed at a much higher level. Proper pointer handling is not always trivial and memory allocation is not either. The philosophia of C++ is that those are gory details that should be hidden to a high level program. For that reason, many SO users advise to never use new[] and delete[] (explicit allocation) but rely on containers which correctly handle the subtilities of automatic deallocation, and copy and move semantics.
For the same reason, references were introduced in the language. At first sight, they just look like disguised pointers to old C programmers, meaning useless syntactic suger, and worse contradictory with the C idiom requiring a pointer to modify a variable from a function (what operator << indeed is at a lower level). But that is exactly what they are for: you can act directly on the variable without explicitly dereferencing it, which removes the risk of forgetting a * somewhere in the code.
And actually, the signature of the stream extractor is:
istream& operator << (istream& in, int& val);
So the function is able to modify the stream itself and the passed variable.
Can some lovely soul help me out with this one :)
Could you please explain each piece of this line of code
and what each Individual piece does? Thank you in advance.
istream & operator >>( istream & input, Registration & R )
ostream & operator <<( ostream & os, const Registration & R )
istream & operator >>( istream & input, Registration & R )
istream& means that object of type istream will be returned by reference.
operator>> is the identifier of the function, it is specifically named so that it overrides the default functionality of the >> operator (similar to how you can override the default functionality the + operator, or operator+() as a "binary" (meaning two) operator (meaning it involves two arguments).
(...) everything within the parentheses are the parameters of the function, they are the data that will be given to the function when it is called to be run.
istream& input indicates that a variable called "input" of type istream will be passed in by reference, meaning that usage of the input variable will refer to the original variable passed in from the location in which it was called and NOT a copy (see: passing by reference and passing by value).
Registration& R indicates that a variable called "R" of type Registration will be passed in by reference (see the definition above). The type Registration seems to be derived from some method for defining a type, such as from a class or a struct.
If you're looking for more information on what an object of type istream is, how it's defined, or what "it does," (along with anything else I mentioned here) I recommend running a search and looking through the wealth of free, available information online.
Generally in C programming language We consider printf and scanf to be functions.
when it comes to cout and cin, in C++ what are they?I mean they cant be functions as they are not followed by parenthesis,so they are not functions.
So what are cout and cin are standard input and output functions?OR something else?
std::cout and std::cin are global objects of classes std::ostream and std::istream respectively, which they've overloaded operator << and >>. You should read about operator overloading.
cout << expr ;
~~~~~~ ~~~~ ~~~~~~~~
object op. argument
It's like a function call; the function is an overloaded operator and a shortcut for this:
cout.operator<<(expr);
or this:
operator<<(cout, expr);
depending on the results of overload resolution
cout is object of type ostream.
cin is object of type istream.
They are global variables, declared in the header <iostream>
Suppose x is an variable ( let integer type ) .We want to put value in it.What we do ?
We write cin>>x .
But we can also put the int data by writing cin.operator>>(x) . This implies cin is an object and operator >> is a function in which x is passed .
The following code snippet is meant to try and extract an integer from a string using a stringstream object and detect whether integer extraction was successful or not. The stringstream class inherits the >> operator to return a reference to an istream instance. How does failed integer extraction lead to myStream being equal to 0 while its str member is still strInput?
stringstream myStream(strInput);
if (myStream >> num){//successfull integer extraction}
else{//unsuccessfull integer extraction
cout<<myStream<<endl;
cout<<myStream.str().c_str()<<endl;}
There is an operator bool() or operator void*() for stream, which returns (something like) !fail() - or in case of void * a NULL when it failed. So, if the stream hasn't failed, it's fine. The operator >> returns a reference to the stream object, so the compiler says "Hmm, can't compare a stream object to truth, let's see if we can make a bool, or void * from it, yes we can, so let's use that.
The answer is in the operator that converts std::ios to void* (replaced with an operator to convert basic_ios to a bool in C++11):
A stream object derived from ios can be casted to a pointer. This pointer is a null pointer if either one of the error flags (failbit or badbit) is set, otherwise it is a non-zero pointer.
This operator gets called when your stream is used in an if, while, or for condition. There is also a unary ! operator for the cases when you need to write
if (!(myStream >> num)) {
...
}
I am learning operator overloading. "out" is being used instead of "cout" when overloading "<<" operator. I don't understand why.
ostream &operator<<( ostream &out, const IntList &L ) {
out << "[ ";
for (int k=0; k< L.numItems; k++) {
out << L.Items[k] << ' ';
}
out << ']';
}
I want to ask differences between cout and out and what happens if I use cout instead of out.
Thanks for answers.
What you are looking at is a overloaded "stream insertion" operator, allowing some custom class to be written to an ostream object using the typical cout << myObject syntax.
The variable in this case is called out because that's the name they've given to the ostream object being passed into the function, which may be any output stream, whether it's cout or an fstream or a stringstream. It's just a variable name, and they could have called it blah and written:
ostream &operator<<( ostream &blah, const IntList &L ) {
blah << "[ ";
// ...
}
Typically you choose a variable name which is descriptive, and out as a name for an output stream is pretty descriptive.
cout would be an especially bad variable name, as it is strongly associated with std::cout, used for writing specifically to the standard output stream. This code doesn't write specificially to standard output, it writes to any ostream object via the << operator so they've chosen a more generic name for their ostream argument.
I want to ask differences between cout and out and what happens if I use cout instead of out. Thanks for answers.
In this case, an ostream& (out) is a parameter passed to the function. This allows the operator<< to work on any ostream.
cout is a specific ostream instance - the standard output stream. If they used cout here, you wouldn't be able to use the << operator on cerr (the standard error stream) or any other ostream. If you replaced the out with cout in the body, any time you used this on a different ostream, it'd be written to cout. (Of course, if you changed the parameter to be named cout, that wouldn't happen - but it would be very misleading to anybody looking at this code, as people would expect that the code writes to the standard output stream, not to the stream being passed in.)
In general, you only would want to use cout as a name if you are specifically referring to std::cout - the standard output stream, as using it in other contexts would be very confusing.
out is the name of the ostream object passed to the overloaded operator (inside the implementation of the operator).
The overloaded operator allows you to write code like this
IntList i;
cout<<i;
or
cerr<<i;
In the implementation if you substituted out with cout, then the second call
cerr<<i;
would print to standard output whereas it should have printed to standard error.
The critical thing here is really the types in the function signature: as long as it's a freestanding function with two parameters - one of type std::ostream& and the other able to be matched by the value to be streamed, then the function body will be invoked. It should return a reference to the stream to allow chaining (as in if (cout << firstIntList << secondIntList)).
The actual parameter names are whatever you feel like, as long as they're not reserved words. I tend to use "os", as in output-stream.