How do I capture the numbers for an array on a single line?

0

I have to write a C ++ code in a question where the user first inserts a number that determines the size of an array, and then inserts in a single line, separated by spaces, the numbers of that array so that stored. How do I capture these numbers on a single line? And what function to use to check if the amount of elements that has been inserted matches the size of the array? (so there is not the error of writing more numbers than the size / space)

    
asked by anonymous 15.03.2017 / 05:42

3 answers

0

Thomas, regardless of whether or not a homework assignment will give you a code for you, you can ask for the size of the array for the user as follows:

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

with size already set to create array . Using the same method that we get the size, we ask for the items of the array however I advise using a string to store, giving a split for whitespace in the string that the user typed, depending on which method you use, will return you a array with all elements of string .
With this array it is easier to check if array size matches the size of the user input, I hope it helps.

    
15.03.2017 / 14:31
0

You can use a StringStream to read data continuously.

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

while (ss >> a) {
    //fazer algo com os números
}
    
15.03.2017 / 18:04
0

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

    
16.03.2017 / 00:06