注册 登录
编程论坛 C++教室

.txt读取中的问题

y605302737 发布于 2013-02-18 21:31, 334 次点击
在读取.txt时遇到一个问题
txt文件是:
y x z
yyyy yyyyy
xxxxxxxxxx
zzzz zzzzz
读取程序
程序代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

int main()
{
    using namespace std;
    ifstream fin;
    fin.open("name.txt");
    if(!fin.is_open())
    {
        cerr<<"cannot open"<<endl;
        exit(EXIT_FAILURE);
    }
    string item;
    int count=0;
    getline(fin,item,'\n');
    while(fin)
    {
        ++count;
        cout<<count<<item<<endl;
        getline(fin,item,'\n');
    }
    cout<<"over gamme"<<endl;
    fin.close();
    return 0;
}
输出结果
1y x z
2yyyy yyyyy
3xxxxxxxxxx
4zzzz zzzzz
over gamme
不过将while(fin)改为while(fin.good())后的结果为:
1y x z
2yyyy yyyyy
3xxxxxxxxxx
over gamme
这是为什么,求高手指教! 谢谢!

4 回复
#2
szwape2013-02-19 00:43
程序中 cout<<count<<item<<endl; 有输出count 所以会有1 2 3 4
读取完最后一个数据后 fin是真 fin.good()返回的是价所以没有第
四行数据 具体的你在查查资料
#3
sbmqj2013-02-19 01:08
学习了
#4
rjsp2013-02-19 08:52
楼主,你的代码跟谁学的?换个人吧,别学废了。cerr<<endl可以忍,冗余的getline也可以忍,但那个exit实在是……
回到你的问题 while(fin) 最终判断调用的 fail(),它和good()并不是完全互补的,起码还差个eof。
也就是,fail()不将eof当作fail,good()将eof当作非good

btw:
程序代码:
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    using namespace std;

    ifstream fin( "name.txt" );
    if( !fin )
    {
        cerr << "cannot open\n";
        return 1;
    }

    int count = 1;
    for( string item; getline(fin,item); ++count )
    {
        cout << count << item << endl;
    }
    cout << "over gamme" << endl;
    fin.close();

    return 0;
}

#5
y6053027372013-02-20 17:44
回复 4楼 rjsp
弱弱的问一句:exit有什么问题 ,我是菜鸟!
1