Joe_Rose
Joe_Rose

Reputation: 48

unable to read integers from txt file to vectors

I can't seem to read any of the following integers from my txt file into my vector. I had cout the first element of the vector just to test to see if the vector is taking in the elements correctly. But the program .exe keeps crashing when i run it. Unless i remove the cout line

#include <iostream> 
#include <cstddef> 
#include <cstdlib> 
#include <fstream>
#include <string>
#include <vector>
using namespace std;


int main(int argc, char** argv) 
{
fstream fin;
char choice_readfile;
int rowcount;

    do                                          //verify choice to read from file is Y,y or N,n
    {
        cout << "Do you wish to read from file (Y/N)? (file name must be named students.txt)" <<     endl;          //choice for user to read from external file
        cin >> choice_readfile;
            while(cin.fail())     
            {
                cin.clear();
                cin.ignore(80,'\n');
                cout << "Please Re-Enter choice" << endl;
                cin >> choice_readfile;             // choice to read from file
            }
    }
    while(choice_readfile != 'Y' && choice_readfile != 'y' && choice_readfile != 'N' && choice_readfile != 'n');

    if(choice_readfile == 'Y' || choice_readfile == 'y')
        {
            fin.open("students.txt", ios::in|ios::out); //opens mygrades.txt 
            if(fin.fail())
            {
                cout << "Error occured while opening students.txt" << endl;
                exit(1);
            }
            fin.clear();           
            fin.seekg(0);     

            string line;     
            while( getline(fin, line) )       //counts the rows in the external file
            rowcount++;          

            cout << "Number of rows in file is " << rowcount << endl; 



            cout << endl;
        }


int i=0, value;enter code here
vector<int>a;
while ( fin >> value ) {
    a.push_back(value);
}


     cout << a[0];
  return 0;
 }

Upvotes: 0

Views: 54

Answers (1)

Captain Obvlious
Captain Obvlious

Reputation: 20063

After you count the number of lines in the file the input offset is at the end of the file. You need to reset it to the beginning of the file before you start reading the integer values. You can reset the input offset with seekg like so.

fin.seekg(0); // move input to start of file.
while ( fin >> value )
{
    a.push_back(value);
}

Upvotes: 1

Related Questions