How to take multiple inputs in the same line in C++?
You can do this simply by cascading the the cin
operator. If you write a code in this way:
int a,b;
cout << "Enter value of a" << endl;
cin >> a;
cout << "Enter value of b" << endl;
cin >> b;
then the program execution would be in this way:
Enter value of a
10
Enter value of b
20
But to do this in a single line, you can write the code in this way:
cout << "Enter the values of a and b" << endl;
cin >> a >> b; //cascading the cin operator
The program execution now goes thus:
Enter the values of a and b
10 20
If you enter both values this way (separating them with a space), then it works the way you want it to - being in the same line.
Also, in the first snippet, if you remove the endl
keyword, you can also have it all in one line but I don't think that's what you want.
Also see: CASCADING OF I/O OPERATORS | easyprograming.
How to have all the inputs on the same line C++
The behavior depends on the input provided by the user.
Your code works as you want, if the user would enter everything (e.g.14:53
) on the same line and press enter only at the end:
Demo 1
Now you can have a better control, if you read a string and then interpret its content, for example as here:
string t;
cout << "\n\tTime: ";
cin >> t;
stringstream sst(t);
int timeHours, timeMinutes;
char c;
sst>>timeHours>>c>>timeMinutes;
Demo 2
How to get multiple inputs in one line in C?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
Related Topics
How to Iterate Over the Words of a String
What Is the Copy-And-Swap Idiom
What Are Copy Elision and Return Value Optimization
Resolve Build Errors Due to Circular Dependency Amongst Classes
What Are the Differences Between a Pointer Variable and a Reference Variable
Why Isn't Sizeof For a Struct Equal to the Sum of Sizeof of Each Member
What Is This Weird Colon-Member (": ") Syntax in the Constructor
Iterator Invalidation Rules For C++ Containers
How to Remove "Noise" from Gcc/Clang Assembly Output
How to Read and Parse CSV Files in C++
What Is a Smart Pointer and When Should I Use One
Accessing an Array Out of Bounds Gives No Error, Why
What Is a Lambda Expression in C++11
Where Do I Find the Current C or C++ Standard Documents
How to Access a Local Variable from a Different Function Using Pointers