如何让这个C++代码从用户那里读取五个整数而不是一个整数?

How do I get this C++ code to read five integers from the user instead of one?

本文关键字:整数 五个 一个 读取 C++ 代码 那里 用户      更新时间:2023-10-16

我正在上一门初级编程课程,我们使用C++,我被困在几个作业上。请原谅我以后可能不好的术语。我正在编写的基本程序的一部分要求"写下 5 个整数:",然后用户可以选择整数并返回一条消息"您编写了整数:n1 n2 n3 n4 n5"。有几个这样的问题,我不允许使用多个相同类型的变量。问题是用户可以用 n1 n2 n3 n4 n5 hello 来回应,而 hello 应该被忽略。我该如何实现此目的?

如果我们暂时假设我们只写下一个整数而不是 5,那么也许下面的代码会起作用。

#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Write down an integer: "
<< flush;
cin >> num;
cout << "You wrote the integer: "
<< num
<< endl;   
}

但是我如何使用五个整数来做到这一点。此外,我如何忽略额外的问候?我断言cin.ignore 会以某种方式在这里使用。

如果您想重复该过程 5 次,您可以复制粘贴它,但这绝对不是一个好的做法。更好的是使用循环/循环,例如for

您还需要将所有 5 个整数存储到内存中。您可以使用 5 个变量 (int n1, n2, n3...(,但同样,这不是一个很好的做法,正如您所说,在您的情况下这是不允许的。解决方案是使用一个数组,该数组可以容纳相同类型的多个值。

下面是一个带有解释注释的工作示例:

int nums[5];                 // this array will hold 5 integers
int n;
cout << "Write down 5 integers:" << endl;
for (n = 0; n < 5; ++n) {    // run code in the braces 5 times
cin >> nums[n];          // store typed integer into nth position of the array
}
cout << "You wrote: ";
for (n = 0; n < 5; ++n) {    // run code in the braces 5 times
cout << nums[n] << " ";  // print integer at nth position of the array
}

注意:可以说numsn属于同一类型,int。在这种情况下,您可以将数组nums扩展到 6 个项目的大小,并使用最后一个(您可以将其称为nums[5](作为循环的索引变量。