0

C++ ifstream を使用してテキスト ファイルからデータを読み込もうとしていますが、何らかの理由で以下のコードが機能しません。このファイルには、スペースで区切られた 2 つの数値が含まれています。ただし、このコードは何も出力しません。誰が私に何が間違っているのか説明できますか?

#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");
}
4

1 に答える 1

2

成功した外部エンティティとの相互作用を常にテストする必要があります。

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";
}
于 2013-07-31T23:20:14.783 に答える