M
M
Max Suprunenko2015-10-09 16:05:51
C++ / C#
Max Suprunenko, 2015-10-09 16:05:51

How can I enter multiple data in one line?

How can I enter multiple data in one line?
Provided that the user himself enters the number of times entered data.
Num Need to be entered

for (int i = 0; i < num; i++)
 {
   std::cin >> mass[i];
   result += mass[i];
  }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vladimir Petrigo, 2015-10-09
@msuprunenko

You can do this:

int num; // количество вводимых элементов
vector<Type> storage; // хранилище элементов

while (num != 0) {
    Type tmp = 0;
    
    cin >> tmp;
    storage.push_back(tmp);
    --num;
}

Provided that you use either a standard type, or a type for which the operator for extracting data from a stream is overloaded.

M
MiiNiPaa, 2015-10-09
@MiiNiPaa

In your current code, you can enter as many values ​​as you like on a single line: the >> operator separates values ​​with whitespace. It doesn't matter if it's newlines or spaces.

T
Tlito, 2015-10-09
@tlito

if (num==3) cin >> mass[0] >> mass[1] >> mass[2] ;
if (num==4) cin >> mass[0] >> mass[1] >> mass[2] >> mass[3] ;
if (num==5) cin >> mass[0] >> mass[1] >> mass[2] >> mass[3]  >> mass[4];

...

A
Alexey Serebryakov, 2015-10-09
@VoltSilver

A very strange assignment.

Provided that the user himself enters the number of times entered data.
number of times , not the amount of data. Why this perversion? If it is the number of times, then it is logical to assume that they enter data several times and press enter. If it's just an unknown number of some data, isn't it easier to declare a charm of an unknown size, take the entire string and put it there, splitting it according to a predetermined separator, as Stanislav suggested?
Or then voice the entire task, and not just what belongs to this code fragment.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question