如何创建一个数组,使用户知道他们是越野的
How to create a array that lets user know they are out-of-bounds?
我正在尝试创建一个程序,该程序可以帮助用户创建从任何整数开始的数组索引。它还应在执行/访问距离的数组组件期间通知用户。
这就是我到目前为止的。
#include <iostream>
using namespace std;
int main(){
class safeArray;
};
const int CAPACITY=5;
我将数组的容量设置为5,以便有一个限制。让用户能够超越界限。
class safeArray() {
userArray= new int [CAPACITY];
用户将能够为数组中的每个插槽创建一个新的int值。
cout <<"Enter any integers for your safe userArray:";
if (int=0;i<CAPACITY;i++) {
cout<<"You are in-bounds!";
}
else (int=0;i>CAPACITY;i++){
cout<<"You are OUT-OF-BOUNDS!";
cout<<endl;
return 0;
};
我使用了一个IF-ELSE语句来检查数组下标?我是C 的新手,因此对如何简化错误或方法的任何澄清都会有所帮助。谢谢。
您的if语句应该只读:
if (i<CAPACITY && i>0) {
cout<<"You are in-bounds!";
}
else if (i>CAPACITY){
cout<<"You are OUT-OF-BOUNDS!";
cout<<endl;
return 0;
};
另外,i ==容量时的边缘情况会发生什么?您的代码根本无法处理这种情况。
要使这个整洁
if (i<CAPACITY && i>0) { // Or should this be (i<=CAPACITY)??? depends on whether 0 is an index or not
cout<<"You are in-bounds!";
} else {
cout<<"You are OUT-OF-BOUNDS!";
cout<<endl;
return 0;
};
而不是处理内存管理,您可以使用标准容器,例如sTD :: vector for Dynamic" arrays"或std :: dramay for固定大小数组。
std :: Array在所有主要编译器上的开销为零,并且在C数组周围或多或少是C 包装器。
为了让用户知道何时何时超出范围,大多数标准容器都提供at(std::size_t n)
方法(例如STD :: vector :: at),这些方法可以为您检查所有的愤怒并投入std :: out_of_range exception提供无效的索引/位置时。
您现在要做的就是捕获该异常,并在您愿意的情况下打印一条消息。这是一个小例子:
#include <iostream>
#include <array>
int main() {
std::array<int, 12> arr;
try {
std::cout << arr.at(15) << 'n';
} catch (std::out_of_range const &) {
std::cout << "Sorry mate, the index you supplied is out of range!" << 'n';
}
}
实时预览-IdeOne.com
相关文章:
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- C++LDAP检查用户是否是特定组的成员
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 直接在 unordered_map 的方法中使用哈希,而不是生成哈希的用户定义对象
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 我怎样才能有 2 个程序并让用户选择他们想要使用的程序?
- 在C++中,创建'n'数量的对象的推荐方法是什么,其中n是用户定义的。我该怎么做?
- 如何检查用户输入是 1 还是 2
- 检查用户是否是 Windows 中本地计算机上的管理员C++
- 用do-nile循环编写程序,并要求其选择用户选择是/否
- 如何创建一个数组,使用户知道他们是越野的
- 他们是如何编写MSVC++调试器的
- PHP Web服务器集成到本地运行的C++exe?他们是如何互动的
- 验证用户输入是5位数字
- 当用户已经是管理员时,通过C++激活管理员 [以管理员身份运行]
- 使用整型变量检查用户输入是整型还是字符串
- 将Xaml文本框转换为double,但如何验证用户输入是double,而不是windows 8应用程序的c++中的字符串
- 是否可以判断交互式用户会话是自动启动还是用户手动登录?
- "anonymous structs"标准吗?而且,真的,他们*是什么*?