【问题标题】:How can I handle the info I get from file while reading in c++?在使用 C++ 阅读时,如何处理从文件中获取的信息?
【发布时间】:2015-02-26 21:11:42
【问题描述】:
int i = 5;
char c = 'n';
string st = "cool";
ofstream my("we.txt");
my <<st<<","<<c<<","<<i<<","<<endl;
string s;

ifstream your("we.txt");
while(your){

    getline(your, st, ',');
    your>>c;
    your.ignore(1);
    your>>i;
    your.ignore(1);
    cout<<st<<","<<c<<","<<i<<endl;
}
my.close();

我什至不知道 your.ignore(1) 代表什么,但它以某种方式起作用。问题是它打印了两次结果,为什么? 有人可以解释我如何处理我写在文件中的信息吗?如果我想在文件中保存 3 信息字符串交易、双倍价格和已售出的字符 (y/n),关于我拥有的每件商品,我该如何管理它? 它看起来像这样 天伯伦, 40, n; 古驰,10,是的; ……等等……

我现在需要它,因为明天我要考试,感谢您的帮助,对不起我的英语!

【问题讨论】:

标签: c++ file stream fstream


【解决方案1】:

至于双重打印的问题,这是因为eofbit 标志直到您从文件末尾之外读取后才设置。这意味着您的循环将迭代一次到多次。

我建议您改为使用 getline 来读取 complete 行(在循环条件下),然后使用例如std::istringstream 解析行。

例如也这样做

while (std::getline(your, fullLine))
{
    std::istringstream istr(fullLine);

    getline(istr, st, ',');
    istr >> c;
    // etc.
}

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2014-10-15
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多