很棒的!从标准输入文件流读取多行数据并且存放到文件---两种实现;标准输入流到文件再到标准输出流

//认为空格,换行符,tab键都是一个字符串的结束标志 
#include<cstdio>
#include<iostream>
#include<fstream>
using namespace std;

int main(){
	ofstream ofs("L7_F0_P5.txt");
	if(!ofs){
		cout<<"Error opening file\n";
		return 1;
	}
	string sentence;
	cout<<"Enter a sentence: ";
	//从输入流为起点
	//输入流一个一个放置到sentence变量中
	//将变量一个一个输入到ofs中并且加上换行符 
	//直到cin流中不能读出数据放置到sentence 
	while(cin>>sentence){
		ofs<<sentence<<"\n";
	}
	ofs.close();
	return 0;
} 


//以换行符作为一行的标志,以行为单位存放到文件中

//从cin输入流放置到sentence变量中
//读取一行getline(cin,sentence); 
#include<cstdio>
#include<iostream>
#include<fstream>
using namespace std;
 
int main(){
	//fstream 默认是ios::in|ios::out 模式 
	ofstream ofs("L7_F0_P5.txt");//直接就是写入流 
	if(!ofs){
		cout<<"Error opening file\n";
		return 1;
	}
	string sentence;
	cout<<"Enter a sentence:\n";
	while(cin){
		getline(cin,sentence);
		ofs<<sentence<<"\n";
	}
	ofs.close();
	return 0;
} 

从标准输入流写入到文件,再重定位到开头,从文件写入到标准输出流

//注意重置光标 
//getline(cin,sentence);从cin中获取一行放到sentence 
//create a file and then write it to the standard output
//先放入标准输入流,再一个一个读取到变量,并放到文件流中
//然后重置光标到开头fs.seekg(0)
//然后从里面依然使用getline方法,和标准输入流一样的,读取出来句子 
#include<cstdio>
#include<iostream>
#include<fstream>

using namespace std;
int main(){
	fstream fs("L7_FO_P5_c.txt",ios::in|ios::out|ios::trunc);
	if(!fs){
		cout<<"Error opening the file";
		return 1;
	} 
	string sentence;
//	while(cin>>sentence) 
	while(cin){//注意只是当cin不为空的时候,而不是在这里赋值,
	//因为你要记得你赋值是要一行的赋值,而不是说遇到空格就赋值
	//while(cin>>sentence)是看到空格,tab键就赋值的 
		getline(cin,sentence);
		fs<<sentence<<"\n"; 
	}
	//全部转移完毕再输出,注意重置光标了
	 fs.seekg(0);
	 while(fs){
	 	getline(fs,sentence);
	 	cout<<sentence<<"\n";
	 }
	 fs.close();
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值