Question

I'm reading input from a file. I know its format. So I would like to read the input from a file and store it. I am trying to use getline to read in the last line, but the program simply hangs. This is my input file data:

6
1 2 2 -4 45 32
123 4234 -234 34534 54 2344
1 2 2 3 4 -234
2 3 -4 -4 4 234
1 11 123 1234 -12334563 2342
2 -234 -23 23 4322 2342
op 2

The first value in the input file states the number of rows/columns the square matrix has. Then you have the square matrix itself. Finally, you have an operation code.

This is my code:

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

using namespace std;

int main()
{
    int i,j,matlim;
    int num;
    string matrixlimit;
    string inputfile;
    string operation;
    ifstream data;
    vector< vector<int> > mat1storage,mat2storage;

    cout<<"Please enter an input file name: ";
    cin>>inputfile;    

    data.open(inputfile.c_str());
    if(data.is_open())
    {
    data >> matlim;
    while(!data.eof())
    {
        for(i = 0;i<matlim;i++)
        {
            vector<int> mat1row;
            for (j = 0;j<matlim;j++)
            {
                data >> num;
                mat1row.push_back(num);
            }
            mat1storage.push_back(mat1row);
        }

        getline(data,operation);
        cout << operation;

    }
 }
 data.close();
}

When I do a simple "data >> operation" in a loop to read that last line from the file the program works without a hitch. But when I try using getline it doesn't work... What am I doing wrong? Thank you.

No correct solution

OTHER TIPS

Getline reads data and store into a string until the delimination character is found.

The delimination character is \n

Insert a blank newline after op 2 in you text file and it should work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top