A slightly more idiomatic solution avoiding using new/delete and native arrays.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int vecSize;
cout << "Digite o tamanho do vetor: ";
cin >> vecSize;
vector<int> vetor;
cout << "Digite os elementos do vetor: ";
for (int i = 0; i < vecSize; i++)
{
int val;
cin >> val;
vetor.push_back(val);
}
cout << endl;
cout << "Números digitados (" << vetor.size() << "):\n";
for (int num : vetor)
{
cout << num << endl;
}
}
In practice, when making data entry always makes consistency of read values, then a slightly more realistic example would be this below:
#include <iostream>
#include <vector>
using namespace std;
enum { MAX_VEC_SIZE = 100 };
int main()
{
int vecSize;
// -------
// leitura do tamanho do vetor
cout << "\nDigite o tamanho do vetor: ";
if (!(cin >> vecSize))
{
cerr << "erro na leitura do tamanho do vetor\n";
exit(1);
}
if (vecSize < 1)
{
cerr << "erro, tamanho do vetor precisa ser maior que zero\n";
exit(1);
}
if (vecSize > MAX_VEC_SIZE)
{
cerr << "erro, tamanho do vetor deve ser menor que " << (MAX_VEC_SIZE+1) << "\n";
exit(1);
}
// -------
// leitura dos elementos do vetor
vector<int> vetor;
cout << "\nDigite os elementos do vetor:\n";
for (int i = 0; i < vecSize; i++)
{
int val;
if (!(cin >> val))
{
cerr << "erro na leitura do elemento " << i << " do vetor\n";
exit(1);
}
vetor.push_back(val);
}
// -------
// exibicao dos elementos do vetor
cout << "\nElementos do vetor (" << vetor.size() << "):\n";
for (int num : vetor)
{
cout << num << endl;
}
// -------
}
That’s all for now Folks.
Have you ever tried to do anything? What is your difficulty ? Put what you have managed to do so far. ;)
– Victor Tadashi
I tried to work with strings, but I had trouble with the sign " - " .
– Gabriel Pastori
I tried to remove the values from the string.
– Gabriel Pastori
cin >> umaVariavel
reads a piece of data (separating by blank spaces). You can, for example: 1. read the amount of elements for a variable (e. g,n
); 2. Create a vector of the variable size you read in the first line (e. g,vetor[n]
); 3. Read each line element inside a loop. As per Vitor’s comment, it’s much easier to help you if you edit the question including an example code.– Anthony Accioly