-2

I am new to programming and I have a data.txt file with the following content:

bumbumbow

1 0 3 9 8

bumbumbum

1 0  3 9 :0

I want to read the line 2: 1 0 3 9 8 and to turn it into integer numbers but I have an error.

error_image

What is the problem? Here is my code:

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

std::fstream& GotoLine(std::fstream& file, unsigned int num) {
    file.seekg(std::ios::beg);
    for (int i = 0; i < num - 1; ++i) {
        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return file;
}

int main() {
    int result, i = 0;
    std::vector<int> Array;
        using namespace std;
        std::fstream file("data.txt");

        GotoLine(file, 2);

        std::string line2;
        std::getline(file, line2);





        for (int result; std::getline(file, line2); result = std::stoi(line2))
        {
            Array.push_back(result);

            std::cout << "Read in the number: " << result << "\n\n";
        }


        return 0;

}

thanks in advance guys

Flame_Phoenix
  • 16,489
  • 37
  • 131
  • 266
Van
  • 53
  • 8

1 Answers1

0

The crash occures due to calling std::stoi() with a wrong parameter "1 0 3 9 8".

You need to replace std::getline(file, line2); result = std::stoi(line2) inside the for loop with something splitting line2 into tokens and calling std::stoi() for those tokens. You can see how to split, for example, here: Right way to split an std::string into a vector<string>

Community
  • 1
  • 1
GMichael
  • 2,726
  • 1
  • 20
  • 30