0

I am trying to read an txt file row by row and write those rows into a vector Each row has an integer value like 1586794757328642

My code is below

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main ()
{
  std::ifstream file("input.txt");
  std::string str;

  std::vector<int> myVect;

  while (std::getline(file, str)) {
    std::cout << str << "\n";
    int myint = std::stoi(str);
    myVect.push_back(myint); 
  }
}

However, I got the following error:

1586794757328642
terminate called after throwing an instance of 'std::out_of_range'
  what():  stoi
Aborted (core dumped)

What am I missing?

JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
uguros
  • 356
  • 2
  • 6
  • 19
  • 2
    See [the documentation for `std::stoi`](https://en.cppreference.com/w/cpp/string/basic_string/stol). `std::out_of_range` means that the number you read is too big to fit in an `int`. Try `long long myint = std::stoll(str);` – Yksisarvinen May 05 '20 at 14:26
  • @Yksisarvinen I tried long, it worked. Many thanks! – uguros May 05 '20 at 14:47

0 Answers0