Reputation: 1
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
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