C++ Input and Output Functions
Posted on December 14, 2022 • 2 minutes • 215 words
1. Output Functions.
The output functions display the results to the user.
Syntax:
#include <iostream>
std::cout << "message" ;
std::cout << variables;
Example:
#include <iostream>
int main() {
// print strings
std::cout << "Welcome to #anooptube\n";
int age = 18;
double salary = 12000.50;
// print the variables
std::cout << age << std::endl;
std::cout << salary << std::endl;
// print two or more variables
std::cout << "Your age is: " << age << " and salary is: " << salary << std::endl;
return 0;
}
To print a new line, use std::endl or \n
2. Input Functions.
Data is accepted from the user through input functions
Syntax:
#include <iostream>
std::cin >> variable_name ;
Example:
#include <iostream>
int main() {
int age;
std::cin >> age;
return 0;
}
Sample Program
Print name and age from user.
#include <iostream>
int main() {
// accept name from user
std::string name;
std::cout << "Enter your name:";
std::cin >> name;
// accept age from user
int age;
std::cout << "Enter your age:";
std::cin >> age;
// print the result
std::cout << "Your name is: " << name << std::endl;
std::cout << "Your age is: " << age << std::endl;
return 0;
}
std::string is a data-type in c++. For more refer string