所以,我有这个循环:
int counter1 = 0;
ifstream incard;
string card;
string cardname;
stringstream out;
while (counter1 < 4) {
counter1 = counter1 + 1;
out << counter1;
out << ".card";
card = out.str();
cout << card;
system("PAUSE");
incard.open(card.c_str());
incard >> cardname;
cout << cardname << endl;
incard.close();
out.str("");
}
1.卡包含文字“天使”
2.card包含文本“Devil”
3.card包含文字“Firaxis”
4.card包含文本“Robert”
这是我得到的输出:
1.cardPress any key to continue . . .
Angel
2.cardPress any key to continue . . .
Devil
3.cardPress any key to continue . . .
Devil
4.cardPress any key to continue . . .
Devil
任何人都可以帮助我解释一下我做错了什么,为什么不读取2.card之外的任何一个卡片文件?
答案 0 :(得分:0)
incard.open("")
将尝试再次使用文件名“1.card”打开文件,这可能不是您想要的(?)您可能还想移动系统(“PAUSE”);循环之后。如果您只想将其打印到控制台,也不需要stringstream。
int counter1 = 0;
ifstream incard;
string card;
string cardname;
incard.open(card.c_str());
while (counter1 < 4) {
counter1++; // Lots shorter than coutner1 = counter1 + 1, but does the same.
incard >> cardname;
cout << counter1 << ".card : " << cardname << endl;
}
incard.close();
system("PAUSE");
答案 1 :(得分:0)
我猜测流在某个时刻进入eof状态,从那时起,尝试读取什么也没做。你需要重置你的流,或者更好的是,把它放在循环中。
通常,将变量声明为尽可能接近其使用。
for (int counter1 = 1; counter1 <= 4: ++counter1) {
stringstream out;
out << counter1 << ".card";
string card = out.str();
cout << card;
system("PAUSE");
ifstream incard(card.c_str());
string cardname;
incard >> cardname;
cout << cardname << endl;
}
请注意如何在重置时节省代码。