Learn how to take user input and display output in C++ using cin, cout, getline, and formatting techniques.
namespace std
using namespace std;
.
namespace std
?cout
and cin
, belong to the std (standard) namespace. To use these functions, we either:
std::
(e.g., std::cout
, std::cin
).using namespace std;
to avoid repeatedly typing std::
.using namespace std;
using namespace std;
std::
prefixes. However, in larger projects, explicitly using std::
is preferred to avoid naming conflicts.
cout
(character output) for printing to the console.
cout
sends data to the console.<<
is the insertion operator.endl
moves the cursor to a new line.cout
as a loudspeaker:
cout << "Hello!";
→ The speaker announces “Hello!”.endl
→ Moves to the next line like taking a breath before speaking again.cin
(character input) to take user input.
cin
takes input from the user.>>
is the extraction operator.age
variable.cin
as a microphone that listens to your input.
cin >> age;
→ The microphone records your response.cin
.
cin
cin
stops taking input when it encounters a space. To take full-line input, use getline()
.
getline()
:getline(cin, fullName);
reads the entire line including spaces.setw
, fixed
, and setprecision
from <iomanip>
.
fixed
ensures decimal precision.setprecision(2)
limits to 2 decimal places.Error | Cause | Solution |
---|---|---|
Missing output | Forgot cout or << | Ensure cout and << are used correctly |
Input not working | cin doesn’t read spaces | Use getline(cin, variable); for full-line input |
Incorrect formatting | Wrong usage of setprecision | Use fixed before setprecision |
cout
for output.cin
for input.getline()
for multi-word input.iomanip
.