Unable to print all integer values

advertisements

I would like to print integer values in a file by reading it.

The code:

    int temp;
    char* trainname;
    trainname="dfg.txt";
    ifstream trainfile;
    trainfile.open(trainname);
    if(!trainfile){
        cout<<"Cannot open file!"<<'\n';
        exit(1);
    }
    while(trainfile >> temp)
        cout << temp << " ";
    trainfile.close();

dfg.txt: 1 2 we er rf 5

output: 1 2

The problem is that it does not print 5.


Read to a temporary string first and then use std::stoi to try to parse an integer from it, and if it succeeds, output it:

std::string temp;

while(trainfile >> temp) {
    try {
        std::cout << std::stoi(temp) << " ";
    }
    catch(const std::invalid_argument&) {
        // not a valid number
    }
}