首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >结束数组输入(C++行业标准)

结束数组输入(C++行业标准)
EN

Stack Overflow用户
提问于 2016-09-02 18:34:15
回答 2查看 181关注 0票数 1

我编写的代码正在工作,但我觉得可能有一种更好、更标准的方法来结束数组的输入,而这一点我可能不知道。所讨论的代码在getInputForArray()中,如果在整数输入上检测到cin.fail(),则通过停止循环来实现。有更好的办法吗?谢谢大家。

代码语言:javascript
复制
#include <iostream>
using namespace std;

int sumOfArray(int arr[], int arrlen);
void getInputForArray(int arr[], int arrlen);

int main() {
    const int LIST_SZ = 256;
    int mylist[LIST_SZ];
    // Zero out the array
    for (int i = 0; i < LIST_SZ; i++)
        mylist[i] = 0;
    // Get user input for array
    getInputForArray(mylist, LIST_SZ);
    // Print the sum of all the numbers in the array
    cout << "\nThe sum is: " << sumOfArray(mylist, LIST_SZ) << endl;
    return 0;
}

int sumOfArray(int arr[], int arrlen) {
    int total = 0;
    for (int i = 0; i < arrlen; i++)
        total = arr[i] + total;
    return total;
}

void getInputForArray(int arr[], int arrlen) {
    cout << "Input any non-numerical value to denote the end of your input\n";
    for (int i = 0; i < arrlen; i++) {
        if (!cin.fail()) {
            cout << "Please input a value for the [" << i
                 << "] position of the array: ";
            cin >> arr[i];
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-02 20:29:33

其他答案涉及EOF (或输入结束)选项。

OP可以修改用户输入检查,以便在输入两次非数字输入时停止循环。我还考虑了使用std::vector而不是原始数组的更好做法。

这是一项可能的执行:

代码语言:javascript
复制
std::vector<int> getDataFromInput( size_t max_data )
{
    using std::cout;

    std::vector<int> v;
    std::string value;

    bool stop_reading = false;

    while ( v.size() < max_data )
    {
        cout << "Please input a value for position [" << v.size() << "] of the vector: ";
        // input a string, if End of Input, stop reading
        if ( !(std::cin >> value) ) break;
        try
        {   // if the user entered a valid number, add it to the vector
            int num = stoi(value);
            v.push_back(num);
            stop_reading = false;
        }
        catch ( const std::invalid_argument &e )
        {
            if ( stop_reading ) break;
            cout << "You entered a non-numerical value.\nPlease, enter another "
                 << "non-numerical value to stop input or a number to continue\n";
            stop_reading = true;
        }
        catch ( const std::out_of_range &e )
        {
            cout << "The value entered can't be represented by an int.\n";
        }
    }

    return v;
}

编辑

正如Lightness races in orbit所指出的:

通过发送EOF来停止输入是更“行业标准”。您通常可以在使用^D (Linux/Mac)或^Z (Windows)的终端上这样做。

因此,您可以将我以前的片段简化为:

代码语言:javascript
复制
std::vector<int> getDataFromInput( size_t max_data )
{
    using std::cout;

    std::vector<int> v;
    std::string value;

    while ( v.size() < max_data )
    {
        cout << "Please input a value for position [" << v.size()
             << "] of the vector: ";
        if ( !(std::cin >> value) ) break;
        try
        {
            int num = stoi(value);
            v.push_back(num);
        }
        catch ( const std::invalid_argument &e )
        {
            cout << "You entered a non-numerical value.\n";
        }
        catch ( const std::out_of_range &e )
        {
            cout << "The value entered can't be represented by an int.\n";
        }
    }

    return v;
}
票数 0
EN

Stack Overflow用户

发布于 2016-09-02 19:16:40

你可以试试这样的东西。

代码语言:javascript
复制
void getInputForArray(int arr[], int arrlen) {
    char c = 0;
    size_t size = 0;
    cout << "Press escape (ESC) to stop inputting values" << endl;

    while(size < arrlen) {
        cout << "Enter a number for position " << size << " of the array: ";
        cin >> arr[size++];

        fflush(stdin);
        c = getchar();
        if(c == 27) { // check for the escape key
            break; // jump out of the loop
        }

        // Check non-numeric values.
        if(cin.fail()) {
            cout << "Error: numerical values only!" << endl;
            cin.clear(); // clear the input
            size--; // go back to previous position
        }
    }
}

或者,您可以通过更改行if(c == 27)来检查EOF (文件的结尾),该行检查if(c == EOF)的转义键。EOF是一个宏,因为它的值与系统有关。但是,我不推荐这种选择,因为每个系统上的密钥序列是不同的。Ctrl+Z适用于DOS或CP/M系统,Ctrl+D用于类Unix系统,Ctrl+\用于AmigaOS等.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39298782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档