How to Have All the Inputs on the Same Line C++

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



Leave a reply



Submit