问题
So, I have this loop:
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.card contains text "Angel"
2.card contains text "Devil"
3.card contains text "Firaxis"
4.card contains text "Robert"
This is the output I get:
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
Can anyone help me shed some light on what I'm doing wrong, why is it not reading either of the card files beyond 2.card?
回答1:
incard.open("")
will try to open the file a second time with the filename "1.card", which is probably not what you want ( ?) You may also want to move the system("PAUSE"); to after the loop. You also don't need the stringstream if you just want to print it to console.
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");
回答2:
I'm guessing the stream goes into eof state at some point and from then on trying to read does nothing. You either need to reset your stream, or better yet, put it inside the loop.
In general, declare variables as close to their use as possible.
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;
}
Note how this saves you code on resetting things.
来源:https://stackoverflow.com/questions/16405630/infile-open-refuses-to-read-the-variable-in-the-file