cout and cin in cpp with example
cout in c++
- cout is a statement that is used to display an output over a console.
- cout is an object of ostream class which is defined in the iostream header file.
there are two ways to use cout:
- first way to use cout is by writing std every time before it.
#include<iostream>
int main()
{
std::cout<<"this is my";
std::cout<<" first message";
return 0;
}
- second way is by using the statement "using namespace std" after including the header file. (recommended)
#include<iostream>
using namespace std;
int main()
{
cout<<"this is my";
cout<<" first message";
return 0;
}
how to break the line while using cout
by using endl ,you can break the line.example:
#include<iostream>
using namespace std;
int main()
{
cout<<"this is my"<<endl;
cout<<" next message";
return 0;
}
how to display the data of variables in c++
example:
#include<iostream>
using namespace std;
int main()
{
int age=10;
float height=4.5;
cout<<"age is "<<age;
cout<<" height is "<<height;
cout<<endl;//breaking the line
//display the variable's value in a single cout
cout<<"age is "<<age<<" height is"<<height;
return 0;
}
cin in c++
- the cin statement is used to take data from a user over a console.
- cin is the object of istream class which is defined in the header file.
- first way to use cout is by writing std every time before it.
#include<iostream>
int main()
{
int age;
float height;
std::cin>>age;
std::cin>>height;
return 0;
}
- second way is by using the statement "using namespace std" after including the header file. (recommended)
#include<iostream>
using namespace std;
int main()
{
int age;
float height;
cin>>age;
cin>>height;
return 0;
}
0 Comments