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 .
Related
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 ;)
void main() {
cout << "Hello World" << endl;
}
I'm not allowed to make any change to the above main function while the output on the screen need to be sth like:
initialize
Hello World
clean up
My thought is that I need to use overloading operator of << . However I need to know what's the data type of the double quoted string following the operator << , otherwise I will not make full use of my redefined << operator. Anyone any thought?
The type of the literal is "array of {suitable number of} const chars", but a better approach might be to have some kind of global object.
(Adding an overload for the array would probably not even work, because the existing overload for char const * would be getting in the way.)
You could redefine std::ostream& operator<< (std::ostream&, const char*). There's one huge problem with this approach: It is undefined behavior. The standard library already defines that function, and you are not allowed to redefine standard library functions.
The key to solving this problem is to recognize that cout is in the global namespace. The solution is simple: Write your own class that overloads operator<< and make a global variable named cout that is an instance of this class. That way you are not running into undefined behavior.
You'll also need to do something with that endl that is in the global namespace.
Your code should look something like
// Insert your code here.
int main () {
cout << "Hello World" << endl;
}
Since this looks like homework, I'll leave the rest up to you.
The type of a string literal is char const[n] where n is the number of characters in the string literal, including the terminating null character. Note, however, that the solution to your problem isn't overloading operator<<(). Instead, you should look at constructors, destructors, and variable with static live-time.
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.
I'm learning pointers and references but I'm having trouble grasping the concept. I need to declare a variable in my main function and then have it initialized through a function by user input, without returning anything. I've tried:
#include <iostream>
using namespace std;
void input(int &num){
cout << "Enter A Number" << endl;
cin >> static_cast<int>(num);
}
int main(){
int x;
input(x);
cout << "The Number You Entered Was " << x << "!" << endl;
return 0;
}
You are doing it correctly, except for that static_cast<int> there. What is it doing there? What made you use that cast?
Get rid of that cast, and it should work. This
cin >> num;
is all you need.
P.S. Just keep in mind that in C++ terminology the term initialize has very specific meaning. Formally, initialization is always a part of variable definition. Whatever changes you do to that variable after the definition is no longer initialization. In your case variable x is declared without an initializer, which means that it begins its life uninitialized (with indeterminate value). Later you put some specific value into x by reading it from cin, but this is no longer initialization (in C++ meaning of the term).
It might be a good idea to declare your x with some determinate initial value, like
int x = 0;
although personally I'm not a big fan of "dummy" initializers.
You should drop the static_cast.
cin >> num;
std::cin's operator>> has overloads that take integral types.
Note that you are not initializing a variable through a function at all. You are assigning a value to a variable by passing a reference to it to a function.
No need for the static_cast stuff. Your function is given a reference to an int, and you want to read an int. Since you've passed a reference to the variable, the changes to it in your input function will be reflected in the caller.
I hav been going over some old hw assignments from a class last semester.
This was a given print function to print out linked list objects.
I don't understand why the overloaded operator takes two parameters and one being an
os object. When we were printing out actual linked list objects on main.cpp, we didn't
need to pass an os object. Also, why is it returning os? Why can't we just use cout
instead of "os <<" ?
Thank you!
template <class T>
void List<T>::print(ostream & os) const
{
os << "<";
ListNode * curr = head;
while (curr != NULL) {
os << " " << curr->data;
curr = curr->next;
}
os << " >";
}
// overloaded operator<<
template <class T>
ostream & operator<<(ostream & os, const List<T> & list)
{
list.print(os);
return os;
}
By the way the question was asked and how basic it is, I'm going to try to give a very simplistic (albeit rather informal and not so pedantic) answer.
I don't understand why the overloaded operator takes two parameters
and one being an os object
operator<< is a binary operator. It has a left-hand side and a right-hand side. When you write:
cout << 123;
You are invoking this operator with two operands (arguments): 'cout' on the left and an integer, '123', on the right.
When we were printing out actual linked list objects on main.cpp, we
didn't need to pass an os object.
Your print function is a member function or operator of a class. That would implicitly deduce that the first argument, crudely speaking, does not need to be explicitly passed since you already have the 'this' pointer to work with for your list object. That's not the case with non-member operators as you don't have an implicitly deduced 'this' object to work with already for the left-hand side operand.
When you write code like this:
my_list.print(cout);
You can think of it as actually passing in two arguments, 'my_list' and 'cout'. Even though you don't write it explicitly, you have access to 'my_list' through 'this' along with its members. That's not the case if you wrote the print function as a non-member, like so:
template <class T>
void print(const List<T>& my_list, ostream& os);
That's also the case with your operator which is not a member function.
Also, why is it returning os?
Returning a reference to ostream is what allows us to write statements like this:
cout << "hello " << "world";
First we invoke operator<<(cout, "hello ") which then gives us another ostream reference to work with which then allows us to proceed to invoke operator<<(cout, "world"). If it returned void, for example, it would not allow us to invoke that operator twice in one statement since we'd be trying to output "world " with void as the left-hand operand.
Why can't we just use cout instead of "os <<" ?
cout basically implements the ostream interface. So does ofstream, ostringstream, and other types of output streams. By writing it in terms of the basic interface required and not some specific ostream derivative, you allow the code you write to work with stdio streams, file streams, stream streams, and others. Basically it makes your code very general and reusable which is something you should strive to do when practical. You'll learn about this subject more as you tackle the concept of polymorphism.
Because it is a global non-member function. With the member function version, the first parameter is implicitly the invoking object, this. That means that your class always has to be on the left hand side. With the non-member function, it's an explicit parameter; this way, you can specify any type you want, and overload operators for classes that you can't modify the source for (as long as at least one parameter is a user-defined type).
The reason why you use os is so that it works with file streams and everything (anything that inherits from ostream), instead of just cout.
It returns os so that you can do more operator<< calls on the return value. This enables operator chaining, like w << x << y << z, which is the same as operator<<(operator<<(operator<<(w, x), y), z). If you return void or something, you would have to stop at w << x because you can't do anything with the return value of void.
I don't understand why the overloaded operator takes two parameters and one being an os object. When we were printing out actual linked list objects on main.cpp, we didn't need to pass an os object.
Yes you did: when you say cout << x, you are passing cout and x to operator<<.
Also, why is it returning os?
To make cout << x << y possible. This is parsed as (cout << x) << y, i.e. it inserts y into the return value of cout << x.
Why can't we just use cout instead of "os <<" ?
Because sometimes you want to output to another stream than standard output.
When we were printing out actual linked list objects on main.cpp, we
didn't need to pass an os object.
Yes, you did.. something like cout << obj;, where cout is the os output stream.
Also, why is it returning os? Why can't we just use cout instead of "os <<" ?
This allows chaining: cout << obj << " " << obj2;
Why can't we just use cout instead of "os <<" ?
That would hard-wire the output stream, so you couldn't write to file or any other output.