作为第一步,添加错误检查,即替换您当前的代码
#include <iostream>
int main()
{
size_t array_size;
size_t sum;
std::cin >> array_size; //let's say array_size = 10000
int* _nums = new int[array_size];
for(int i = 0; i < (int)array_size; i++)
{
//everything goes fine if I put something like 500 as the array_size
std::cin >> _nums[i];
}
return 0;
}
与例如
#include <iostream>
#include <vector> // std::vector
#include <stdexcept> // std::runtime_error, std::exception
#include <stdlib.h> // EXIT_FAILURE, EXIT_SUCCESS
#include <string> // std::string
bool throwX( std::string const& s ) { throw std::runtime_error( s ); }
void cppMain()
{
int array_size;
std::cin >> array_size; //let's say array_size = 10000
std::vector<int> nums( array_size );
for( int i = 0; i < array_size; ++i )
{
//everything goes fine if I put something like 500 as the array_size
std::cin >> _nums[i]
|| throwX( "Oops, input failed!" );
}
}
int main()
{
try
{
cppMain();
return EXIT_SUCCESS;
}
catch( std::exception const& x )
{
cerr << "!" << x.what() << endl;
}
return EXIT_FAILURE;
}
免责声明:现成的代码,可能需要修复拼写错误。