gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:12:19 24 4
gpt4 key购买 nike

<分区>

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

#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];
}
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com