infile.open拒绝读取文件中的变量 [英] infile.open refuses to read the variable in the file

查看:484
本文介绍了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包含文字「Angel」

1.card contains text "Angel"

2.card包含文字Devil

2.card contains text "Devil"

3.card包含文字Firaxis

3.card contains text "Firaxis"

4.card包含文本Robert

4.card contains text "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之外的卡片文件?

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?

推荐答案

我猜流会进入eof状态一些点,从那时起,试图阅读什么也没有。

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.

这篇关于infile.open拒绝读取文件中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆