Taking multiple inputs in C++ is a basic operation that is done very often. In some situations, we need to take multiple inputs at once with a space between them. This tutorial will discuss how to take multiple inputs in C++ with space.
Steps
1. Declare variables and choose their data types: Before taking inputs, variables must be declared and their data types must be chosen. For example, if we want to take two integers, we can declare them as follows:
1 |
int a, b; |
2. Use the “cin” function to take inputs: The “cin” function is used to take inputs in C++. In this case, we can use “cin” to take multiple inputs with space between them. The code for this is as follows:
1 |
cin >> a >> b; |
In this code, we are taking two integer inputs (a and b) with a space between them. The “>>” operator is used to separate the inputs.
3. Display the inputs: After taking inputs, we can display them to verify that they have been taken correctly. The code for displaying inputs is as follows:
1 |
cout << "a = " << a << ", b = " << b << endl; |
In this code, the “cout” function is used to display the values of variables “a” and “b”. The “<<” operator is used to separate the variables and the “endl” function is used to move the cursor to the next line.
Example
Let’s take a look at an example to understand this concept better. In this example, we will take two integers as inputs with a space between them and then display their values.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> using namespace std; int main() { int a, b; cout << "Enter two integers with a space between them: "; cin >> a >> b; cout << "a = " << a << ", b = " << b << endl; return 0; } |
Output:
Enter two integers with a space between them: 12 34 a = 12, b = 34
Conclusion
Taking multiple inputs in C++ with space is a simple task that can be done easily by using the “cin” function.
We just need to declare variables, choose their data types, and then use “cin” to take inputs. After that, we can display the inputs to verify that they have been taken correctly.