2013-07-31 48 views
0

数据我想使用C++ ifstream的一个文本文件,由于某种原因,下面的代码不工作在数据读取。该文件包含由空格分隔的两个数字。但是,这段代码不会打印任何东西。任何人都可以向我解释什么是错的?ifstream的空白在阅读时有文件

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

你应该,如果你正确地打开该文件,并且您成功地读取输入。从问题描述中,我猜测它无法打开文件。 –

+1

你实际上并没有检查文件是否正常打开。它有可能从未打开过? – Borgleader

回答

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"; 
} 
+0

我觉得无法读取该文件是错误的。不是你应该警告的事情。 –

+0

当使用这个它打印出“警告:无法读取文件内容\ n”。为什么如果不能读取文件的内容? – user2640052

+0

@ user2640052:如果至少有两个字符串由文件中的空格分隔,则不应该失败。您可能需要阅读并测试各个字段,以查看哪一个导致失败。 –