Home > Software engineering >  How to create a function that takes user input n times and returns a pointer to the array (of size n
How to create a function that takes user input n times and returns a pointer to the array (of size n

Time:11-22

So I want to create a function that will allow me to get any number of positive numbers from the user. I have tried vectors which did not handle one variable, just overwriting its value over and over I also tried *array = new int [size] but it didn't work for me. I am new to C . The main problem is that I want to access the value from global scope and that array or anything that will store the data will have a variable size.

Here is a code that works. Now I want it to just for loop over cin >> num1; until i<=var_name.

The thing is I do not have a functioning code anymore:

    int num1, num2, num3;
    int * addresses[3] = {&num1,&num2, &num3};
    
    int * dodatnie_liczby(int var_num) {
        int arr[3 1];
        if (var_num == 3) {
            while (true) {
                cout << "Enter 3 positive integers" << endl;
                cin >> num1;
                if (num1 < 0) {
                    continue;
                }
                else {
    
                    cin >> num1;
                }    
                if (num1 < 0) { 
                    continue;
                }
                else {
    
                    cin >> num1;
                }
                if (num1 < 0) {
                    continue;
                    
                }
                else {
    
                    break;
                }
            }
            return  addresses[3 1];
        }
        
        if (var_num == 2) {
            while (true) {
                cout << "Enter 2 positive integers" << endl;
                cin >> num1;
                if (num1 < 0) {
                    continue;
                }
                else {
                    cin >> num1;
                }
    
                if (num1 < 0) {
                    continue;
                }
                else {
                    break;
                }
            }
            printf("\n");
            return  addresses[2 1];
        }
        if (var_num == 1) {
            while (true) {
                cout << "Enter 1 positive integer" << endl;
                cin >> num1;
                if (num1 < 0) {
                    continue;
                }
                else {
                    break;
                }
            }
            printf("\n");
            return  addresses[1 1];
        }
    }

For tests:

    void zad1() {
        int multiplied_num= *addresses[0];
        int max = *addresses[1];
        for (int i = 1;multiplied_num*i<max;i  ) {
            cout << multiplied_num*i<< endl;
        }
    }
    void zad2() {
        dodatnie_liczby(2);
        int multiplied_num= *addresses[0];
        int number_of_multiples = *addresses[1];
    
        printf("\n");
            for (int i = 1; i <= number_of_multiples; i  ) {
                cout << multiplied_num*i << endl;
            }
    }

What I tried and failed miserably:

    #include <iostream>
    #include <vector>
    using namespace std;
    std::vector<int> result;
    int num1;
    int var_num;
    int *result_arr = new int [var_num 1];
    int *input_times(int var_num) {
        for (int i=0; i< var_num; i  ) {
            int *result_arr = new int [var_num 1];
            cout << "Enter a positive integer" << endl;
            cin >> num1;
            if (num1 < 0) {
                continue;
            }
            else {
                result.push_back(num1);
                result_arr[i] = num1; 
                printf("%p\n", result[i]);
                printf("%p\n", result_arr[i]);
    
                continue;
            } 
    
        return result_arr;
        }
    }

CodePudding user response:

I will answer your question with 4 solution proposals:

  1. Use std::vector as local function variable and return it to caller.
  2. Use std::vector as global variable.
  3. Use new to create a dynamic array locally and return it to caller.
  4. Use newto create a dynamic array globally.

Some notes:

  • Solutions 3 and 4, which use new to allocate owned memory, are strongly discouraged in C .
  • Global variables should in general not be used at all.

So, the only recommended solution is with a std::vector that is defined locally and then returned to the calling function.

Please see this solution below:

#include <iostream>
#include <vector>
#include <limits>

std::vector<int> getPositiveNumbers(const int count) {

    // Define the dynamic storage
    std::vector<int> result{};

    // Give user instruction
    std::cout << "Please enter " << count << " positive numbers:\n";

    do {
        int number{};
        if (std::cin >> number) {
            // Check if number is positive
            if (number >= 0)
                // Yes, the store it
                result.push_back(number);
            else
                // negative number given. Show error message
                std::cout << "\n*** Error: Neagtive value given. Please try again\n\n";
        }
        else {
            // Invalid input given, for example "abc"
            // Show error message
            std::cout << "\n*** Error: invalid input format. Please try again\n\n";
            // Clear error state of std::cin
            std::cin.clear();
            // And ignore all invalid characters in the input buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    } while (result.size() < count);

    // return the vector to the calling instance
    return result;
}
int main() {
    // Call the function
    std::vector<int> values = getPositiveNumbers(3);

    std::cout << "\n\n--------------------------------\nEntered values are:\n";
    for (const int i : values) std::cout << i << ' ';
    std::cout << "\n\n";
}

Solution with global std::vector:

#include <iostream>
#include <vector>
#include <limits>

// Global variable
std::vector<int> result{};

void getPositiveNumbers(const int count) {

    // Give user instruction
    std::cout << "Please enter " << count << " positive numbers:\n";

    do {
        int number{};
        if (std::cin >> number) {
            // Check if number is positive
            if (number >= 0)
                // Yes, the store it
                result.push_back(number);
            else
                // negative number given. Show error message
                std::cout << "\n*** Error: Neagtive value given. Please try again\n\n";
        }
        else {
            // Invalid input given, for example "abc"
            // Show error message
            std::cout << "\n*** Error: invalid input format. Please try again\n\n";
            // Clear error state of std::cin
            std::cin.clear();
            // And ignore all invalid characters in the input buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    } while (result.size() < count);


}
int main() {
    // Call the function
    getPositiveNumbers(3);

    std::cout << "\n\n--------------------------------\nEntered values are:\n";
    for (const int i : result) std::cout << i << ' ';
    std::cout << "\n\n";
}

Solution with new. Not recommended:

#include <iostream>
#include <limits>

int* getPositiveNumbers(const int count) {

    // Define the dynamic storage
    int* result = new int[count] {};

    // Give user instruction
    std::cout << "Please enter " << count << " positive numbers:\n";

    // Index in result
    int index = 0;

    do {
        int number{};
        if (std::cin >> number) {
            // Check if number is positive
            if (number >= 0)
                // Yes, the store it
                result[index  ] = number;
            else
                // negative number given. Show error message
                std::cout << "\n*** Error: Neagtive value given. Please try again\n\n";
        }
        else {
            // Invalid input given, for example "abc"
            // Show error message
            std::cout << "\n*** Error: invalid input format. Please try again\n\n";
            // Clear error state of std::cin
            std::cin.clear();
            // And ignore all invalid characters in the input buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    } while (index < count);

    // return the vector to the calling instance
    return result;
}
int main() {
    // Call the function
    int* values = getPositiveNumbers(3);

    std::cout << "\n\n--------------------------------\nEntered values are:\n";
    for (int i = 0; i < 3;   i) std::cout << values[i] << ' ';
    std::cout << "\n\n";

    // You must delete the newed dynamic storage.
    delete[]values;
}

Solution with new and a global variable. Not at all recommended:

#include <iostream>
#include <limits>

int* values{};

void getPositiveNumbers(const int count) {

    // Define the dynamic storage
    values = new int[count] {};

    // Give user instruction
    std::cout << "Please enter " << count << " positive numbers:\n";

    // Index in result
    int index = 0;

    do {
        int number{};
        if (std::cin >> number) {
            // Check if number is positive
            if (number >= 0)
                // Yes, the store it
                values[index  ] = number;
            else
                // negative number given. Show error message
                std::cout << "\n*** Error: Neagtive value given. Please try again\n\n";
        }
        else {
            // Invalid input given, for example "abc"
            // Show error message
            std::cout << "\n*** Error: invalid input format. Please try again\n\n";
            // Clear error state of std::cin
            std::cin.clear();
            // And ignore all invalid characters in the input buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    } while (index < count);

}
int main() {
    // Call the function
    getPositiveNumbers(3);

    std::cout << "\n\n--------------------------------\nEntered values are:\n";
    for (int i = 0; i < 3;   i) std::cout << values[i] << ' ';
    std::cout << "\n\n";

    // You must delete the newed dynamic storage.
    delete[]values;
}


  • Related