C++,ifstream对象调用getline按行读取文本文件

本文介绍了如何在C++中使用ifstream对象结合getline函数按行读取文本文件。通过示例代码展示了getline的用法,并分析了在不同情况下读取文件时可能遇到的问题,特别是针对第一行数据未被读取的情况进行了探讨。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

C++ Prime P255  本来是学习该页的用 vector<string> files

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;


void main()
{
	ifstream input;
	string s,filename = "c:/ludashi.txt";
	vector<string> files;
		files.push_back(filename);
		
	vector<string>::const_iterator it = files.begin();

	while (it!=files.end()) {
				input.open(filename.c_str());
				if(!input)break;
				while(input>>s)cout<<s<<endl;
				input.close();
				input.clear();
				++it;
	}

}


 

 

 

自己捣鼓了一个用getline 读文件:

getline此时的用法 直接 getline(ifile,s)

ifile: 读文件的流,即ifstream对象 

s:  string 对象

// 标准IO库.cpp
//P253

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

ifstream& readfilebyline(ifstream& in){
      string s;
			if(!in)exit(EXIT_FAILURE);// 流出错
			while(getline(in,s))
				cout<<s<<endl;
	 
     	in.close();
		in.clear();
	return in;
}

void main()
{
    string filename = "c:/ludashi.txt";
	ifstream ifile(filename.c_str());
	if(ifile.is_open())	
		readfilebyline(ifile);
}

 

参考 http://wenku.baidu.com/view/590cce0abb68a98271fefaf4.html

中的第四条:

getline(cin,s) ; // 就是把输入的一行赋予字符串s, 把cin换成ifstream的文件流ifile 即可.

因为 ifstream 由 istream 派生而来....继承了其中的方法getline,因此用法雷同.

 

另外可以参考:

http://www.cnblogs.com/kevin2010_vip/archive/2010/02/03/1662853.html

 

//  如果是这样,则遇到空格就算读了一次

ifstream& readfilebyline(ifstream& in){
      string s;
        while(in>>s)cout<<s<<endl;
    return in;
}

运行结果是 原txt文件中的第一行没有, 原因估计是 在 mian() 中给ifile(filename.c_str()) 是就读过了 ?

 

 

//--- 

再改,直接在main () 中, 第一行还是没有读到,奇怪了.如下:

 

 

// 再改改 : 直接在 main中 用getline 就可以把第一行读出:

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值