In this simple tutorial, we will learn to get input from the user in C++. We will learn to take integer, character, string with spaces as an input. If you want to learn about the data types in C++ then go through the following tutorial.
Take Integer and Character as an Input from User
The program is simple, to take an input we use cin input stream present in C++. The program asks the user to enter an integer and displays that value on the screen. Then it also asks the user to enter a character and the value is again printed on the screen.
#include <iostream>
using namespace std;
int main()
{
// integer
int val;
cout << "Enter the Number: ";
cin >> val;
cout << "Integer Value " << val;
// Character
char ch;
cout << "\n\nEnter a Character: ";
cin >> ch;
cout << "Character value: " << ch;
return 0;
}
Output:
Enter the Number: 25
Integer Value 25
Enter a Character: A
Character value: A
Get String Input with Spaces
We can get a string with spaces from the user with the use of gets() function or function. Use them in the following way in the program.getline()
gets(str);
getline(cin, str);
1. Take String input with Spaces using gets()
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char str[200];
cout << "Enter the String: ";
gets(str);
cout << "String entered: " << str;
return 0;
}
Enter the String: This is simple2code.com
String entered: This is simple2code.com
2. Take String Input with Spaces using getline()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Enter the String: ";
getline(cin, str);
cout << "String entered: " << str;
return 0;
}
Enter the String: I am simple2code.com
String entered: I am simple2code.com