You can also take user input at runtime, which is not difficult at all. For this, you can use cin stream, which stands for console input.
#include
using namespace std;
int main() {
int number;
char ch;
cout << "Enter a number: ";
cin >> number;
cout << "Enter a character: ";
cin >> ch;
cout << "number = " << number << " character = " << ch;
return 0;
}
12
d
number = 12 character = d
>> operator after cin, which is called the input extraction operator.cin stream.You can also take multiple inputs in a single line, like this:
char ch, ch1;
cin >> ch >> ch1;
However, in reality, if you run the program in example 1, it may not wait for the character input and produce unexpected results.
When you input 5 and press Enter, the input stream stores:
5\n
which means the number 5 is assigned to number but the newline character (\n) remains in the input buffer.
Now, when cin >> ch; executes, instead of waiting for a character input from the user, It may reads the leftover newline (\n) from the buffer. As a result, ch is assigned \n, and the program may not wait for user input.
Add cin.ignore() before reading ch to clear the buffer:
cin.ignore();
cin >> ch;
Taking string input using cin has a limitation.
cin is not ideal for taking multi-word strings because it considers spaces (' ') as input separators.characters: To take multi-word string input, you can use an array of characters.
#include
using namespace std;
int main()
{
char name[50];
cout << "Enter a string: ";
cin.get(name, 50);
cout << "You entered: " << name << endl;
return 0;
}
My name is Rameen
My name is Rameen
name is a variable that will store the full string input, including spaces.getline() (Better Approach)Instead of using character arrays (char[]), you can use C++’s string type with getline():
#include
#include
using namespace std;
int main()
{
string name;
cout << "Enter a string: ";
getline(cin, name); // Reads a full line of input including spaces
cout << "You entered: " << name << endl;
return 0;
}
My name is Rameen
My name is Rameen
getline() over cin.get()string, so there’s no need to manually allocate a fixed array size (char[50] has a limit). As a result, it avoids buffer overflows. Note: If getline() follows a cin >> statement, add cin.ignore() to clear the buffer before calling getline() as we did in the example 1.
No Comments