简体   繁体   English

我在C ++中从用户获取函数输入,添加到数组并打印该数组时遇到麻烦

[英]I'm having trouble in C++ geting input from a user in a function, adding to an array, and printing that array

I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array. 我正在学习c ++,试图让用户在函数中输入4个数字,然后简单地打印数组。

int getFourNums();
int main(int argc, char** argv){

    int getNums;

    getNums = getFourNums();

    cout << "The array is: " getNums << endl;
}

int getFourNums(){

    int i;

    int myArray[4];
    cout << "Enter 4 nums: ";
    for(i = 0; i < 4; i++){
        cin >> myArray[i];
    }
    return myArray[i];

As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." 到目前为止,它让我得到了四个数字,但是打印的结果是“数组为:0”。 I'm not quite sure why the array is seemingly not populating. 我不太确定为什么数组似乎没有填充。

Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. 你的根本问题是int getFourNums()只能返回一个整数,而不是他们的数组。 The next problem is that functions cannot return raw arrays for historical reasons. 下一个问题是由于历史原因,函数无法返回原始数组。 Your choices are to return a std::array , a struct containing the array, pass the array by reference into the function, or return a std::vector . 您的选择是返回std::array ,包含std::arraystruct ,通过引用将数组传递给函数或返回std::vector My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array , you should probably default to std::vector unless you have a good reason otherwise. 我对此应用程序的偏好是std::vector它很灵活,尽管效率不如std::array ,但除非有充分的理由,否则您可能应该默认为std::vector Your getNums code would then look like: 您的getNums代码如下所示:

std::vector<int> getFourNums() {
    std::vector<int> result;
    cout << "Enter 4 nums: ";
    for(int i = 0; i < 4; i++){
        int v;
        cin >> v;
        result.push_back(v);
    }
    return result;
}

To print the vector, see this question . 要打印矢量,请参阅此问题 My personal preference would be a range-based for loop over the vector; 我的个人偏好是基于范围的向量循环。 your tastes may vary. 您的口味可能会有所不同。

One issue in your code is that a loop like 您的代码中的一个问题是这样的循环

for(i = 0; i < 4; i++){
    cin >> myArray[i];
}

will end up with i==4 . 将以i==4结束。 Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour. 因此, return myArray[i]将超出数组范围和/或访问未初始化的值,然后产生未定义的行为。

The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. 但是,主要问题是,在C ++中,您将采用一种非常不同的方法,并使用std::vector类的集合类型而不是普通数组。 See the following code illustrating this. 请参见以下代码对此进行说明。 Hope it helps. 希望能帮助到你。

#include <vector>
#include <iostream>

std::vector<int> getFourNums(){

    int val;
    std::vector<int> result;
    cout << "Enter 4 nums: ";
    for(int i = 0; i < 4; i++){
        cin >> val;
        result.push_back(val);
    }
    return result;
}

int main(int argc, char** argv){
    std::vector<int> fourNums = getFourNums();
    for (auto i : fourNums) {
        cout << i << endl;
    }
}

int getFourNums() will only let you return one int , not the whole array and return myArray[i]; int getFourNums()将只允许您返回一个int ,而不是整个数组,并return myArray[i]; is out of bounds since i == 4 . 由于i == 4而超出范围。 You can only use the range [0,3] as indices for your array. 您只能将范围[0,3]用作数组的索引。 Here's a reworked version with comments in the code. 这是经过重新设计的版本,在代码中带有注释。

#include <iostream>
#include <vector>

// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.

// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.

std::vector<int> getNums(size_t count) {

    // The "array" we'll return with "count" number of
    // default constructed int:s (they will all be 0):

    std::vector<int> myArray(count);

    std::cout << "Enter " << count << " nums: ";

    // A range based for loop that will go through
    // all int:s in "myArray". "num" will be
    // a reference to each int in the vector which
    // means that if you change the value of "num",
    // you'll actually change the value in the vector.

    for(int& num : myArray) {
        // read values into the int currently
        // referenced by num

        std::cin >> num;
    }

    // return the vector by value
    return myArray;
}

// Put main() last so you don't have to forward declare the functions
// it uses

int main() {

    // call getNums with the value 4 to read 4 int:s
    std::vector<int> Nums = getNums(4);

    std::cout << "The array is:";

    // print each int in the vector. There's no need to use
    // a reference to the int:s here since we won't be changing
    // the value in the vector and copying an int is cheap.

    for(int num : Nums) {
        std::cout << " " << num;
    }

    // std::endl is rarely good when you only want to output a newline.
    // It'll flush the buffer with is costly.
    // Make a habit of using "\n" in most cases.

    std::cout << "\n";
}

I see that you want to return entire array but just look at your return type: 我看到您想返回整个数组,但只看您的返回类型:

int getFourNums()

You're returning an integer right? 您要返回整数吗? In this situation the returned integer is always myArray[4] . 在这种情况下,返回的整数始终是myArray[4] Be aware that it's an integer value, you're returning something that doesn't belong to you actually! 请注意,这是一个整数值,您返回的实际上并不属于您!

So what to do? 那么该怎么办? I suggest you to pass your array to function like this: 我建议您将数组传递给这样的函数:

 void getFourNums(int myArray[]){
    int i;
    cout << "Enter 4 nums: ";
    for(i = 0; i < SIZE; i++){
        cin >> myArray[i];
    }
}

Now you filled your array. 现在,您已填充阵列。 How to print your array then? 那么如何打印数组? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). 我们不能简单地给出我们的数组名称,并告诉cout像您一样打印它(您实际上不能!)。 Nothing magical here. 这里没什么神奇的。 We're going to print your array's element one by one: 我们将一一打印您数组的元素:

void printFourNumbers(int array[])
{
    for(int i = 0 ; i < SIZE ; ++i)
    {
        cout << array[i] << endl;
    }
}

Finally whole code looks like this: 最后,整个代码如下所示:

#include <iostream>
using namespace std;
const int SIZE = 4;

void getFourNums(int myArray[]);
void printFourNumbers(int array[]);

int main(int argc, char** argv){
    int myArray[SIZE];
    getFourNums(myArray);
    printFourNumbers(myArray);

}

void getFourNums(int myArray[]){
    int i;
    cout << "Enter 4 nums: ";
    for(i = 0; i < SIZE; i++){
        cin >> myArray[i];
    }
}

void printFourNumbers(int array[])
{
    for(int i = 0 ; i < SIZE ; ++i)
    {
        cout << array[i] << endl;
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM