Untitled Document
Untitled Document
The cout object, together with the << operator, is used to output values/print
text:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does
not insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
C++ New Lines
New Lines
To insert a new line, you can use the \n character:
Example
#include <iostream>
int main() {
return 0;
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << "\n\n";
cout << "I am learning C++";
return 0;
}
Another way to insert a new line is with the endl manipulator:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
Both \n and endl are used to break lines. However, \n is most used.
cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
In the following example, the user can input a number stored in the variable
x. Then we print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cout << "Your number is: " << x; // Display the input value
Good To Know
cout is pronounced, "see-out". Used for output, and uses the insertion
operator (<<)
cin is pronounced, "see-in". Used for input, and uses the extraction operator
(>>)
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;