How to capture the numbers for a single line array?

Asked

Viewed 173 times

0

I have to write a code in C++ in a question where, first, the user enters a number that determines the size of an array, and then, insert in a single row, separated by spaces, the numbers of that array for them to be stored. How to capture these numbers in a single line? And what function do you use to verify that the amount of elements you entered matches the size of the array? (to avoid the error of writing more numbers than the size/space)

  • 3

    Put there the code that you tried but didn’t work... (or you’re wanting the group to do their homework?)

3 answers

0

Thomas, whether or not it is a homework I will give you a north to do the code, you can ask for the size of the array p/ the user as follows:

int tamanhoArray;
std::cout << "Informe o tamanho do array: ";
std::cin >> tamanhoArray;

with the size of the p/ create the array. Using the same method we got the size, we asked for the array items but I advise using a string p/ store, giving a split by blanks in the string that the user has typed, depending on the method you use, will return a array with all elements of string.
With that array makes it easier to check whether the array size matches the size of the user input, I hope it helps.

0

You can use a Stringstream to read the data continuously.

int a;
char* stringlida;
stringstream ss(stringlida);

while (ss >> a) {
    //fazer algo com os números
}

0

You need to make dynamic allocation so that the size of the array is defined by the user. Use the "malloc".

Browser other questions tagged

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