【发布时间】:2014-10-17 21:21:59
【问题描述】:
所以我有一个项目(我不希望任何人为我做我的硬件,但我现在对 3 个数据结构中的第一个感到厌烦,这样我就可以开始我的项目了)我需要填写一个通过运行一些文件来匹配映射,我的示例文件设置简单,我需要提取一个 long 作为映射中字符串的值的键,如下所示:
0 A
1 B
2 C
我的对显然是 0 的地方是 A 的关键,这将是这个项目的一个字符串,问题是我的导师也说这将是一种可能的格式:
0 W e b 1
1 W e b 2
2 W e b 3
其中 0 是“W e b 1”的键。我知道我需要在空白处进行划分,但老实说,我什至不知道从哪里开始,我尝试了几种方法,但在第二种情况下我只能得到字符串的第一个字符。
这最终是我所坐的,不用担心整个布尔返回以及我知道整个打开文件和检查它应该发生在这个函数之外的事实,但是我的教授希望所有这些都在这个函数中.
bool read_index(map<long, string> &index_map, string file_name)
{
//create a file stream for the file to be read
ifstream index_file(file_name);
//if file doesn't open then return false
if(!index_file)
return false;
string line;
long n;
string token;
//read file
while(!index_file.eof())
{
getline(?)
//not sure how to handle the return from getline
}
//file read?
return !index_file.fail();
}
【问题讨论】:
-
马上开始,
while(!index_file.eof())is wrong。使用while(std::getline(index_file, line))并在循环体中丢失getline。 始终检查您的 IO 操作是否成功;永远不要假设他们没有失败。