我的代码:
d = {1: ['a', 'b', 'c'], 2: ['d'], 3: ['e','f'], 4: ['g'], 5: ['h', 'i']}
f= lambda x: x[0] if len(x)==1 else x
{i:f(d[i]) for i in d}
它应输出包含的文件但我在命令
中得到了这个111 ahmed yousef lol no yes khaled 15
222 adas asd sdt huy mjmj mjg2 20
0 0
前两行是正确的,但我不知道为什么它会输出最后2个零(0 0)
答案 0 :(得分:2)
条件while(myfile)
只会在某些输入失败后停止。
此时您已经从该输入尝试中打印了零。
每次尝试输入后都必须检查myfile
的状态,看看是否成功。
答案 1 :(得分:2)
充实@Bo's answer,并回答您的comment:
以及我如何在每次尝试输入后检查myfile的状态??
你可以像这样修复你的循环:
void load_books(){
ifstream myfile(path);
if (myfile.fail()){
cout << "coudln't open file" << "\n\n";
}
else{
while (myfile >> book1[i].id >> book1[i].title >> book1[i].p_name
>> book1[i].p_address >> book1[i].aut_name
>> book1[i].aut_nationality >> book1[i].date >> book1[i].status){
cout << book1[i].id << "\ " << book1[i].title << "\ " << book1[i].p_name << "\ "
<< book1[i].p_address << "\ " << book1[i].aut_name << "\ "
<< book1[i].aut_nationality << "\ " << book1[i].date << "\ "
<< book1[i].status << endl;
i++;
}
}
}
由于std:istream& operator>>(std:istream&, T&)
的链式调用返回当前std:istream&
引用,while()
循环中的条件可以解析为std::basic_ios::operator bool
,循环将以很快,运营商评估为false
。
相关参考文件:
子>