小编2go*_*his的帖子

C ++错误:抛出'std :: bad_alloc'实例后终止调用

我编写了下面粘贴的代码,以按声明的顺序执行以下任务:

  1. 读取输入文件并计算其中的条目数
  2. 创建一个适当大小的数组(大小等于条目数)
  3. 返回输入文件的开头并再次阅读
  4. 将条目存储在数组中
  5. 打印出文件中的条目数以及条目本身。

这是我的代码:

#include <iostream>
#include <fstream>
#include <exception>

using namespace std;

int main(int argc, char* argv[]){

    ifstream inFile(argv[1]); //passing arguments to the main function
    int numEntries;

    if(!inFile){
        cout << "file not found" << endl;
        return 1;
    }

    string entry;
    while (!inFile.eof()){ //counting the number of entries
        getline(inFile,entry);
        ++numEntries;
    }

    const int length = numEntries;  //making an array of appropriate length
    int*arr = new int[length];

    inFile.clear();             //going back to the beginning of the file
    inFile.seekg(0, ios::beg); …
Run Code Online (Sandbox Code Playgroud)

c++

7
推荐指数
2
解决办法
4万
查看次数

标签 统计

c++ ×1