C++ 如何在c++;
我只希望从用户处接收小于或等于C++ 如何在c++;,c++,C++,我只希望从用户处接收小于或等于4 这是我的代码: #include <iostream> using namespace std; int main() { unsigned int n; cin>>n; unsigned int arr[n]; for (int i =0 ;i<n ; i++){ if (arr[i]<=4) cin>>arr[i]; } } #包括 使用名称空间std; int
4
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
unsigned int n;
cin>>n;
unsigned int arr[n];
for (int i =0 ;i<n ; i++){
if (arr[i]<=4)
cin>>arr[i];
}
}
#包括
使用名称空间std;
int main()
{
无符号整数n;
cin>>n;
无符号整数arr[n];
对于(int i=0;iarr[i];
}
}
我的代码有什么问题?它接收的数字大于
4
代码的行为未定义。在写入之前,您正在读取数组的元素
然后不检查用户输入的值
注意,可变长度数组不是标准C++(<代码>未签名INTARR[N];< /COD>声明这样的数组)。使用<代码> STD::vector < /COD>改为“< /P>” 实际上,解决这些问题的最佳方法是使用一个好的逐行调试器。
\include
#include <iostream>
using namespace std;
int main() {
unsigned int input = 0u; // Holds user input
unsigned int nextPos = 0u; // Next free position in our array
unsigned int arraySize = 0u; // The size of the dynamic array
unsigned int* array = nullptr; // Pointer to our dynamic array
// Ask the user for the array size
cout << "Please Enter The Array Length" << endl;
cin >> arraySize;
// using array = int[arraySize] wouldn't work because the compiler won't know what value the number is at compile time.
// instead we use the 'new' keyword to allocate some memory while the program is running
// this is called dynamic allocation
array = new unsigned int[arraySize];
// The reason it's a while loop instead of a for loop is to only insert numbers into the array
// when the pass the rule if input <= 4u (the u part just means it's unsigned)
while(nextPos < arraySize) {
// Here we ask for an input and store it in the same named input variable
cout << "Please Enter A Valid Number" << endl;
cin >> input;
// Does the input pass the check?
if (input <= 4u) {
// If so store it in the current position in the array and increment
// the line below is the same as doing
// array[nextPos] = input;
// nextPos = nextPos + 1u;
array[nextPos++] = input;
} else {
// When the input doesn't meet the rule, complain about an invalid number
cout << input << " is an invalid number" << endl;
}
}
// A rule in C++ is that we need to manually release any memory we allocate using new
// it would be 'delete variable' for objects or 'delete[] variable' for arrays
delete[] array;
}
使用名称空间std;
int main(){
unsigned int input=0u;//保存用户输入
unsigned int nextPos=0u;//数组中的下一个空闲位置
unsigned int arraySize=0u;//动态数组的大小
unsigned int*array=nullptr;//指向动态数组的指针
//询问用户阵列大小
不能排列;
//使用array=int[arraySize]不起作用,因为编译器在编译时不知道数字是什么值。
//相反,我们使用“new”关键字在程序运行时分配一些内存
//这称为动态分配
数组=新的无符号整数[arraySize];
//它是while循环而不是for循环的原因是只在数组中插入数字
//当通过规则时,请解释。问题不清楚。用户如何添加第一个数字?您甚至在用户之前检查条件inputs@GoverNator:某些编译器允许将其作为扩展,并在默认情况下将其打开。当您尝试移植到其他平台时,会导致错误。基于显然,不是这样。我应该考虑使用一段时间吗?我会考虑写一个单独的函数来读取每个单独的值。当“代码> STD::向量数组(ARAYSIZE); >下,使用原始的NoPoS=0;NestPoS < ARAYSIZE;<代码> ST::向量数组;数组。保留(数组大小)……(数组,sie()):数组…PurthyBead(输入);…< /代码>如果遇到无法解析为<代码> INT/COD>的东西,请不要忘记重置流。此外,请考虑<代码> STD::vector < /代码>,使用<代码> PurpSuff-<代码>习惯用法。