您的位置:首页 > 其它

文件的输入和输出-cin用法

2013-09-07 12:49 169 查看
#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string.h>
using namespace std;
#define SIZE 256
int main()
{
//////文件的输入和输出使用方法://///////////////

//输出数据到文件的5个步骤:
//1.包含fstream头文件;
//2.建立ofstream对象;如:ofstream ocout;
//3.将对象与文件关联;如:ocout.open("123.txt");
//4.该对象可看作cout对象,可以使用该对象数据输出到文件中,而不是屏幕中;
//	如:ocout << "abcdefg";
//5.关闭与文件的连接。如:ocout.close();
/*
ofstream ocout;
ocout.open("D:\\123.bat");
ocout << "hello world\n";
ocout.close();
*/

//读取文件中的数据的5个步骤:
//1.包含fstream头文件;
//2.建立ifstreamd对象;
//3.将对象与文件关联;
//4.该对象可看作cin对象,使用方法与cin相同;
//5.关闭连接。
/*
char temp[20];
ifstream icin;
icin.open("D:\\123.bat");
icin.getline(temp, 19, 0);
cout << temp << endl;
icin.close();
*/

/*
//读取空格及空格后面的字符
char temp1[SIZE] = {0};
char temp2[SIZE] = {0};
ofstream fout("D:\\1.txt");
cout << "input:";
cin.getline(temp1, SIZE-1, 0);//遇到EOF才停止,所以需要按下ctr+z
int n = strlen(temp1);
temp1[n-1] = '\0';
fout << temp1;
fout.close();
ifstream fin("D:\\1.txt");
fin.getline(temp2, SIZE-1, 0);
fout.open("D:\\2.txt");
fout << temp2;
cout << temp2;
fin.close();
fout.close();
*/
//////////////////////////////////////////////////

////检查文件是否打开//////////////////////////////
//使用is_open()方法检测文件是否打开成功
/*	ofstream fout("D:\\a.txt");
if(fout.is_open() == false)
{
cout << "fout open file false\n";
return -1;
}
fout << "yang qian\n";
fout.close();

ifstream fin("D:\\a.txt");
if(fin.is_open() == false)
{
cout << "fin open file false\n";
return -1;
}
cout << "open file success content is:\n";
char ch;
while(!fin.eof())//未到文件尾循环
{
ch = fin.get();
cout << ch;
}
fin.close();

fout.open("D:\\a.txt", ios::app);
if(fout.is_open() == false)
{
cout << "fout open file false\n";
return -1;
}
fout << "second yang qian\n";
fout.close();

//将重复读入文件的各个标志清 0(重置流);有些版本不要求这么做,VC需要
//建议使用
fin.clear();
fin.open("D:\\a.txt");
if(fin.is_open() == false)
{
cout << "fin open file false\n";
return -1;
}
cout << "open file success content is:\n";
while(!fin.eof())//未到文件尾循环
{
ch = fin.get();
cout << ch;
}
fin.close();*/
/////////////////////////////////////////////////

////cin的用法://////////////////////////////////

/*	int x;
cin >> hex >> x;//hex控制符指定输入的模式为十六进制
cout << x;
*/

/*	char world[12];
cin >> world;			//输入 Hello World
//输出 Hello,cin把空格和换行符作为分隔符看待,遇到空格认为当前输入已经完成
cout << world << endl;
*/

/*	char ch;
ch = cin.get();
cout << "ch:" << ch << endl
*/

/*	//输出时,遇到行结束符endl才刷新缓冲区
//输入时,按Enter键刷新缓冲区并且将数据写入磁盘
char ch;
while((ch = cin.get()) != '\n')
{
cout << ch;
}
*/

/*
//换行符'\n'和Enter键作用的一样的
int c;
c = int('\n');
cout << c << endl;
c = cin.get();	//按下Enter键
cout << c << endl;	//ASCII值和'\n'一样
*/

//回车符'\r'和换行符'\n'是不同的,'\r'作用是回到该行的开头

/*
char ch1[30] = {0};
//从输入流中读取5个字节到ch1中,碰到EOF(文件结束标记)中止
cin.read(ch1, 5);
cout << "string is:" << ch1 << endl;
*/
/////////////////////////////////////////////////
cout << "\nEND" << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: