使用std :: cin将大量数字输入到数组中时遇到了令人沮丧的问题(尽管我不在乎它是否是cin或其他东西)。我必须将多达一百万个整数存储到一个整数数组中,并且已经找到了一个解决方案,出于某种原因,它只适用于842-843的第一个输入。
我的代码:
#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;
}
感谢您的帮助!
答案 0 :(得分:0)
首先,添加错误检查,即替换当前代码
#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;
}
免责声明:袖口外码,可能需要修正拼写错误。