2013-05-06 31 views
0

所以,我有這樣的循環:infile.open拒絕讀取變量文件

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包含文本 「天使」

2.card包含文本 「魔鬼」

3.card包含文本 「Firaxis」

4.card包含文本 「羅伯特」

這爲t他輸出我得到:

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

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

請注意,這是如何節省您的代碼重置事情。