[英]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 个解决方案来回答你的问题:
std::vector
as local function variable and return it to caller.std::vector
作为本地 function 变量并将其返回给调用者。std::vector
as global variable.std::vector
作为全局变量。new
to create a dynamic array locally and return it to caller.new
在本地创建一个动态数组并将其返回给调用者。new
to create a dynamic array globally.new
全局创建一个动态数组。 Some notes:一些注意事项:
new
to allocate owned memory, are strongly discouraged in C++.new
来分配拥有的memory,在C++中是被强烈反对的。 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.