Storing in a vector without pressing ENTER at each insertion

Asked

Viewed 88 times

1

It is necessary to store a sequence of numbers in a vector, but pressing ENTER only at the end of the line.

For example:

ENTRADA: 10 20 30 15 50 <ENTER>
Vetor[] = {10, 20, 30, 15, 50}
  • What language should you do this in? Don’t forget to tag her.

  • I’m sorry. It’s c++

  • Post your implementation attempt also, the idea is to get help, not to ask someone to implement it to Voce.

1 answer

0

If you are using c++ you can use a vector which is simple enough to add numbers as you read them.

As for the reading itself you can do in several ways. One of the most direct is with stringstream. In this scenario the reading can be all made of cin all at once with getline and placed in a stringstream. Then read the number of the stream until finished and added to the vector with the method push_back.

Implementation:

#include <iostream>
#include <sstream>
#include <vector>

int main() {
    std::vector<int> nums; //criar o vector de numeros
    std::string linha; //string para ler a linha toda da consola
    std::getline(std::cin, linha); //ler a linha

    std::stringstream ss; //criar a stream
    ss << linha; //colocar a linha na stream

    int num;
    while (ss >> num){ //le numero da stream testando se chegou ao fim
        nums.push_back(num); //adiciona o numero ao vector
    }

Now to show you can use ranged for loop of c++11 for example:

    for (auto n : nums){
        std::cout << n << std::endl;
    }

If you are not using c++11 or later you can always use the vector in a very classical way:

    for (size_t i = 0; i < nums.size(); ++i){
        std::cout << nums[i] << std::endl;
    }

Exit:

10
20
30
15
50

See code working on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.