jeudi 7 février 2019

Reading whole numbers from a txt file

I am trying to write a programme which:

1) Asks for a filename from the user

2) if it exists it takes in the file and prints out the contents of it

3) If the file does not exist it would use a default configuration

Here is what I have written

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

int main(){



std::vector<int> z{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2};
std::vector<int> v;
std::string filename;

std::cout << "enter initial configuration file name: " << std::endl;
std::cin >> filename;

std::ifstream infile;
infile.open(filename.c_str());

if(!infile.is_open()){
    std::cout << " file not found, using default start configuration" << std::endl;

    for(int i = 0; i< z.size(); i++){
        v[i] = z[i];
    }

    for( int i = 0; i<v.size(); i++){
        std::cout<<v[i];
    }

}

else{

    int tmp;

    while(infile >> tmp){
        v.push_back(tmp);
    }

    for( int i = 0; i<v.size(); i++){
        std::cout<<v[i];
    }

return 0;    
}

}

When it enters the if loop it just freezes does nothing and then the programme terminates. However when it enters the else it works fine.

why is this?

Aucun commentaire:

Enregistrer un commentaire