我正在编写一个简单的 C++ 程序,它为我的程序分配动态内存,然后删除该内存。这是我的程序:
#include <iostream>
#include <new>
using namespace std;
int main ()
{
int i,n;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == nullptr)
cout << "Error: memory could not be allocated";
else
{
for (n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
在上面的程序中,当我输入的值 i(输入数)等于或小于 20 亿时,该程序按预期运行。但是,当我输入超过 20 亿的任何值(例如 30 亿或更高)时,该程序会进入无限循环,而不会在我的 for 循环中输入数字。
当我输入一个非常高的 i 值时,我预计这个程序会失败,说它无法分配内存。
根据我的理解,我认为当我输入一个非常高的 int i 值时,我将超出整数数据类型的界限,但在这种情况下,它应该像我一样在 for 循环中接受我的数字输入那里的 cin 语句而不是进入 for 循环或内存分配应该简单地失败。
当我将 i 的类型从 int 更改为 long 时它可以工作,但我很想知道对于 int 类型的 i,当它在 for 循环中看到 cin 时,为什么它进入无限循环而不是取值?
我在 Mac OS X 上运行这个程序并使用 g++ 编译器编译它。
最佳答案
1) 您正在尝试分配给 int
大于 2147483647 的值,通常是该类型的最大值。
一般来说,如果你想处理这么大的数字,你应该使用 long long int
(或来自 <cstdint>
的内容以获得更好的便携性)。
2) 你没有清除 cin
的状态失败后。
下面的代码生成无限循环:
int i = 0;
while (i <= 0)
{
std::cout << "Enter a number greater than 10..." << std::endl;
std::cin >> i;
}
可以这样解决:
int i = 0;
while (i <= 0)
{
std::cout << "Enter a number greater than 10..." << std::endl;
if (!(std::cin >> i))
{
std::cin.clear(); // Clear error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Remove incorrect data from buffer
}
}
3) 您正在尝试创建一个非常大的数组。你需要几个 GiB 对此的连续内存。即使你成功分配了数组,它仍然是一个设计问题。您应该使用许多较小的阵列或使用/创建合适的容器。
关于c++ - 无限循环不接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28532530/