如何让这个C++代码从用户那里读取五个整数而不是一个整数?
How do I get this C++ code to read five integers from the user instead of one?
我正在上一门初级编程课程,我们使用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
}
注意:可以说nums
和n
属于同一类型,int
。在这种情况下,您可以将数组nums
扩展到 6 个项目的大小,并使用最后一个(您可以将其称为nums[5]
(作为循环的索引变量。
相关文章:
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- C++ 如何比较n个排序的整数向量以找到互元素?
- 在链链表中手动插入第五个元素
- 编写一个读取五个整数并执行一些任务的C++程序
- 数组中所有元素的最新最小元素的第五个位置
- 向下四舍五入到五个c++的最近倍数
- 如果我有五个 Win32 静态控件,如何使用特定的前景色设置其中一个?
- 如何让这个C++代码从用户那里读取五个整数而不是一个整数?
- 使用继承和虚拟功能应用五个规则
- 将结构的值设置为五个可能之一
- 在向量数组中获得前五个最大的结果
- 在一个作用域中推送五个对象指针,然后检查对象的布尔值是否为 false,会给出错误
- 我正在编写一个代码,该代码从用户那里为公司中的五个项目输入数量
- 前五个自然数的总和
- 允许用户在迷宫游戏中最多移动五个空间
- 在五个节点的图上应用 Dijkstra 算法
- Qt在五个Phonon::VideoWidget中播放相同的视频
- 我找到所有的单词,有五个字母在一个向量的字符串与equal_range,它一直抛出一个错误,说它没有排序