c++ 我如何创建一个函数,接受用户输入的整数到一个数组,并退出函数,如果非整数输入输入?

jogvjijk  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(113)

我是这学期在入门课上接触C++的新手,而且我之前没有太多的编码经验。感觉这应该不是一个很难的任务,但它仍然难倒了我。
我创建了一个函数fillArray(),它接受用户输入并将其输入到一个名为numArray的数组中。如果我只输入数值输入,这个函数工作得很好,如果我不尝试提前退出循环,但我需要它在我尝试这样做时正确退出。
我尝试在fillArray()中编写if/else语句,以便在输入非数字输入时跳出循环,但这没有达到预期的效果。
作业的详细信息在我程序上方的注解文本中。我甚至还没有谈到问题的reverseArray()部分,因为我一次解决一个问题。

// arrays.cpp

/* Write a program that uses the following functions:
Fill_array() takes as arguments the name of an array of int values and an array size. It prompts the
user to enter int values to be entered in the array. It ceases taking input when the array is full or when
the user enters non-numeric input, and it returns the actual number of entries.
Show_array() takes as arguments the name of an array of int values and an array size and displays
the contents of the array.
Reverse_array() takes as arguments the name of an array of int values and an array size and reverses
the order of the values stored in the array.
The program should use these functions to do the following:
fill an array, display the array, reverse the array, display the array, reverse all but the first and last
elements of the array, and finally, display the array.
Name your program arrays.cpp */

#include <iostream>

using namespace std;

void fillArray(int array[], int size)
{
    int inputNum;

    for(int index = 0; index < size; index++)
    {
        cout << "Enter an integer: ";
        cin >> inputNum;

        if((inputNum > -1000) && (inputNum < 1000))
            array[index] = inputNum;
        else
            break;   
    }
}

void showArray(int array[], int size)
{
    for(int index = 0; index < size; index++)
    {
        cout << array[index] << endl;
    }
}

int main()
{
    int numArray[10];

    fillArray(numArray, 10);
    showArray(numArray, 10);

    return 0;

}

我尝试了在fillArray()中的if/else选择中在线找到的许多不同语句,如果输入非数字输入,我无法使函数正确退出循环。

nwnhqdif

nwnhqdif1#

解决办法很简单,但由于某些原因,很少有人被教导:检查cin >> inputNum的返回值。

cout << "Enter an integer: ";
        if (cin >> inputNum)
            array[index] = inputNum;
        else
            break;

从技术上讲,cin >> inputNum的结果是cin本身,这就是为什么你可以把它链接在一起,但是如果用户输入的不是数字,那么流将设置它的fail位。然后,当您调用if (cin)时,它会检查流是否设置了任何错误位。因此,这可以用来检查是否所有先前的操作都成功了。
不相关的,你的函数应该return false或抛出一个异常,让调用者知道它没有完成它的工作。

相关问题