在数组中输入大量整数
Input huge amounts of integers into an array
在使用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;
}
谢谢你的帮助!
作为第一步,添加错误检查,即替换当前代码
#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;
}
免责声明:即兴代码,可能需要修复拼写错误。
相关文章:
- 正在验证c++中用户的整数输入
- 如何用字符终止整数输入循环?
- 以C++为单位将已知数量的整数输入正确读取到向量中
- C++ - 重复 std::getline() 作为用户整数输入?
- C++程序,将整数输入转换为字符的问题
- 将整数输入数组的方法比 scanf() 或 cin 更快?
- 程序终止,而不是继续整数输入验证循环
- 如何在C 中输入未知数的整数输入
- 在C 中遇到了如何从用户输入直到输入的整数输入
- C++ 通过 range for 循环将整数输入到矢量中;随机 0
- 如何在 C++ 中包含整数输入的前面的 0
- 仅接受整数输入
- 拒绝用户整数输入 c++ 中的某个值
- 我想通过scanf将字符和整数输入到结构中
- 此代码段如何验证整数输入
- 验证整数输入C++?
- 循环直到整数输入在所需范围内无法处理非数字字符输入
- 整数输入 拒绝非整数输入并在C++中请求另一个输入
- 如何保存用户的整数输入,并返回字符串值?
- 除 "6" 作为最右边数字的整数输入外,任何整数输入都可以使用,但任何数字(如 ...6.导致分段错误,为什么?