user2640052
user2640052

Reputation: 1

ifstream reading in blanks when there is data in file

I'm trying to read in data from a text file using c++ ifstream and for some reason the code below doesn't work. The file contains two numbers separated by a space. However this code doesn't print anything out. Could anyone explain to me what is wrong?

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void readIntoAdjMat(string fname) {
    ifstream in(fname.c_str());
    string race, length;
    in >> race >> length;
    cout << race << ' ' << length << endl;  
    in.close();
}

int main(int argc, char *argv[]) {
    readIntoAdjMat("maze1.txt");
}

Upvotes: 0

Views: 349

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

You should always test that interactions with external entities where successful:

std::ifstream in(fname.c_str());
std::string race, length;
if (!in) {
    throw std::runtime_error("failed to open '" + fname + "' for reading");
}
if (in >> race >> length) {
    std::cout << race << ' ' << length << '\n';
}
else {
    std::cerr << "WARNING: failed to read file content\n";
}

Upvotes: 2

Related Questions