简体   繁体   English

如何创建一个接受用户输入 n 次并返回指向数组(大小为 n+1)的指针的 function,以便我可以在全局 scope 中访问它的值? C++

[英]How to create a function that takes user input n times and returns a pointer to the array (of size n+1) so I can access its value in global scope? C++

So I want to create a function that will allow me to get any number of positive numbers from the user.所以我想创建一个 function,它允许我从用户那里得到任意数量的正数。 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.我尝试过不处理一个变量的向量,只是一遍又一遍地覆盖它的值我也尝试过*array = new int [size]但它对我不起作用。 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.我是 C++ 的新手。主要问题是我想从全局 scope 访问该值,并且该数组或任何存储数据的内容都将具有可变大小。

Here is a code that works.这是一个有效的代码。 Now I want it to just for loop over cin >> num1;现在我希望它只是循环cin >> num1; until i<=var_name .直到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;
        }
    }

I will answer your question with 4 solution proposals:我将用 4 个解决方案来回答你的问题:

  1. Use std::vector as local function variable and return it to caller.使用std::vector作为本地 function 变量并将其返回给调用者。
  2. Use std::vector as global variable.使用std::vector作为全局变量。
  3. Use new to create a dynamic array locally and return it to caller.使用new在本地创建一个动态数组并将其返回给调用者。
  4. Use new to create a dynamic array globally.使用new全局创建一个动态数组。

Some notes:一些注意事项:

  • Solutions 3 and 4, which use new to allocate owned memory, are strongly discouraged in C++.解决方案3和4,使用new来分配拥有的memory,在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.因此,唯一推荐的解决方案是使用本地定义的std::vector ,然后返回给调用方 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 :全局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 . 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.使用new变量和全局变量的解决方案。 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;
}


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 哪个在C ++中更快:i <= N或i <N + 1 - Which is Faster in C++: i<=N or i<N+1 递归C ++函数,它将整数n的数组作为输入,然后在不使用任何循环的情况下输出数组中的最大值和最小值 - recursive C++ function that takes as input an array of integers n then prints the maximum and the minimum value in the array without using any loops 我如何创建一个接受整数数组及其大小并返回 true 的 c++ 函数 isOdd 是所有数组元素都是奇数 - How could I create a c++ function isOdd that accepts an integer array and its size and returns true is all of the array elements are odd 如何在C ++中创建n行5列的数组,但是n值正在变化 - How to create an array of n rows and 5 columns in C++, but the n value is changing 如何在初始化为唯一指针的动态数组中存储字符串(来自n行的文件)? C ++ - How can I store a string(from a file with n number of lines) in a dynamic array initialized as a unique pointer? C++ 在 C++ 中为大小为 n 的数组的前 m 个元素赋值 - Assign value to the first m elements of an array of size n in C++ 如何使用 SWIG 包装一个 C++ 函数,该函数将 Python numpy 数组作为输入而不显式给出大小? - How can you wrap a C++ function with SWIG that takes in a Python numpy array as input without explicitly giving a size? 如何创建一个大小为 NxN 的方形二维数组,其中 N 由用户提供并填充一定范围内的随机数? - How can I create a square 2d array of size NxN where N is supplied by the user and populated with random numbers at a certain range? 我想在 C++ 中创建一个指向 char 值的指针并获取它的大小,但它不显示任何内容 - I want to create a pointer to a char value in C++ and get its size, but it doesn't display anything 我能告诉C ++中用“new type [n]”创建的数组的大小吗? - Can I tell the size of an array created with “new type[n]” in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM