21天学C++(十七)流

完整目录、平台简介、安装环境及版本:参考《21天学C++ 概览》

十七、

17.1 标准I/0对象

17.1.1 流和缓冲区

  • ios类是输入输出的基类,有一个成员变量是streambuf;
  • streambuf类管理缓冲区,它的成员函数提供了填充、清空、清除和在其他情况下处理缓冲区的功能;
  • istream和ostream类从ios类派生出来,用于专门管理输入和输出行为;
  • iostream从istream类和ostream类中派生出来,提供向屏幕写数据的输入和输出功能;把输出到屏幕的数据流看作是一个字节接一个字节的流;

fstream类提供了文件的输入和输出;

17.2 cin

17.2.1 cin输入:处理来自标准输入设备(键盘)的输入

为各种参数提供的提取运算符>>,包括int,short,long,double,float,char char*等;

如cin>>intVar;相当于调用:

  • istream &operator>>(int&);//按引用传递,能对原始变量进行操作;

17.2.2 cin输入串

char strNmae[50];
cin>>strName;

  • 输入c++,存储为c,+,+,\0来填充,cin会自动用一个空字符来结束字符串;
  • 输入c++ test,cin会把空格或换行符当作分隔符看待,任务输入已经完成,会自动加上一个空字符;

cin>>intVar>>strName; //因为返回istream 引用;

#include <iostream>
using namespace std;
int main(){
	int intVal=0;
	std::cin>>intVal;
	std::cout<<intVal<<std::endl;

	int intVal1,intVal2;
	std::cin >> intVal1 >> intVal2;
	std::cout<<intVal1<<std::endl;
	std::cout << intVal2 << std::endl;

	char strName[50];
	std::cin >> strName;
	std::cout << strName << std::endl;
	std::cin >> strName;
	std::cout << strName << std::endl;
	return 0;
}

执行结果如下:

1
1
2
3
2
3
hello
hello
you
you
请按任意键继续. . .

17.2.3 单字符输入:char c = cin.get();

结束字符Ctrl+Z;

#include <iostream>

int main()
{
	char ch;
	while ( (ch = std::cin.get()) != EOF)
	{
		std::cout << "ch: " << ch << std::endl;
	}
	std::cout << "\nDone!\n";
	return 0;
}

执行结果如下:

abc
ch: a
ch: b
ch: c
ch:

def
ch: d
ch: e
ch: f
ch:


D^C请按任意键继续. . .

17.2.4 单字符输入:char c = cin.get(a);

返回iostream对象,可以连续输入

#include <iostream>

int main()
{
	char a, b, c;

	std::cout << "Enter three letters: ";

	std::cin.get(a).get(b).get(c);

	std::cout << "a: " << a << "\nb: ";
	std::cout << b << "\nc: " << c << std::endl;
	return 0;
}

执行结果如下:

Enter three letters: chen
a: c
b: h
c: e
请按任意键继续. . .

17.2.5 读取字符串:

cin.get(字符数组指针,读取的最大字符数+1,结束字符 )

#include <iostream>
using namespace std;

int main()
{
	char stringOne[256];
	char stringTwo[256];

	cout << "Enter string one: ";
	cin.get(stringOne,256);
	cout << "stringOne: " << stringOne << endl;

	cout << "Enter string two: ";
	cin >> stringTwo;
	cout << "StringTwo: " << stringTwo << endl;
	return 0;
}

执行结果如下:

Enter string one: chen
stringOne: chen
Enter string two: hua
StringTwo: hua
请按任意键继续. . .

17.2.6 读取字符串:

cin.getline(字符数组指针,读取的最大字符数+1,结束字符)

#include <iostream>
using namespace std;

int main()
{
	char stringOne[256];
	char stringTwo[256];
	char stringThree[256];

	cout << "Enter string one: ";
	cin.getline(stringOne,256);
	cout << "stringOne: " << stringOne << endl;

	cout << "Enter string two: ";
	cin >> stringTwo;
	cout << "stringTwo: " << stringTwo << endl;

	cout << "Enter string three: ";
	cin.getline(stringThree,256);
	cout << "stringThree: " << stringThree << endl;
	return 0;
}

执行结果如下:

Enter string one: chen hua p
stringOne: chen hua p
Enter string two: chen hua p
stringTwo: chen
Enter string three: stringThree:  hua p
请按任意键继续. . .

17.2.7 vignore()、peek()、putback()

  • ignore(忽略的最大字符数,结束符);找到结束符之前忽略的最大字符数,然后丢弃换行符;
  • peek():从输入流中查看字符,但是并不提取;
  • putack():想输入流中插入一个字符;
#include <iostream>
using namespace std;

int main()
{
	char ch;
	cout << "enter a phrase: ";
	while ( cin.get(ch) != 0 )
	{
		if (ch == ‘!’)   //用$代替!
			cin.putback('$');
		else
			cout << ch;
		while (cin.peek() == ‘#’) //如果碰到字符#,则忽略
			cin.ignore(1,'#');
	}
	return 0;
}

执行结果如下:

enter a phrase: chen!hua#ping
chen$huaping
chen#####
chen
请按任意键继续. . .

17.3 cout

17.3.1 cout

可以把字符串、整数和其他数值数据写到屏幕;

可以用来格式化数据、按列对齐、按十进制和十六进制写数据;

17.3.2 cout.put()

向输出设备写单个字符;

put返回一个ostream引用,所以可以连续调用;

#include <iostream>

int main()
{
	std::cout.put('H').put('e').put('l').put('l').put('o').put('\n');
	return 0;
}

执行结果如下:

Hello
请按任意键继续. . .

17.3.3 cout.write(字符数组指针,输出最大字符数)

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
	char One[] = "One if by land";

	int fullLength = strlen(One);
	int tooShort = fullLength -4;
	int tooLong = fullLength + 6;

	cout.write(One,fullLength) << endl;
	cout.write(One,tooShort) << endl;
	cout.write(One,tooLong) << endl;
	return 0;
}

执行结果如下:

One if by land
One if by
One if by land 烫烫
请按任意键继续. . .

17.3.4 cout.width(宽度);count.fill(char)

改变输出的宽度,然后马上恢复默认;

填充字符;

#include <iostream>
using namespace std;

int main(){
	cout << "Start >";
	cout.width(25);
	cout << 123 << "< End\n";

	cout << "Start >";
	cout.width(25);
	cout.fill('*');
	cout << 123 << "< End\n";

	cout << "Start >";
	cout.width(5);
	cout.fill('*');
	cout << 123 << "< End\n";

	cout << "Start >";
	cout.width(2);
	cout.fill('*');
	cout << 123 << "< End\n";

	return 0;
}

执行结果如下:

Start >                      123< End
Start >**********************123< End
Start >**123< End
Start >123< End
请按任意键继续. . .

17.4 printf

  • 不提供类型安全检查,也不支持类;
  • printf 使格式化输出变得容易;
#include <stdio.h>

int main()
{
    char *phraseTwo = "Here's some values: ";
    char *phraseThree = " and also these: ";
    int y = 7, z = 35;
    long longVar = 98456;
    float floatVar =  8.8f;
 
    printf(“%s %d %5d”,phraseTwo,y,z);//输出字符串     整型     指定宽度整型
    printf(“%s %ld %f\n”,phraseThree,longVar,floatVar);//输出字符串   长整型    浮点型    

    char *phraseFour = "Formatted: ";
    printf(“%s %5d %10d  %10.5f\n”,phraseFour,y,z,floatVar); //输出字符串   指定宽度整型   指定宽度整型  指定精度浮点型

    return 0;
}

执行结果如下:

Here's some values:  7    35 and also these:  98456 8.800000
Formatted:      7         35     8.80000
请按任意键继续. . .

17.5 文件的输入输出 ifstream ofstream

ofstream和ifstream对象从iostream对象中派生;

读或写结束之后,需要用close()关闭文件;

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

int main(){
	char fileName[] = "file.txt";
	char buffer[255];    

	ofstream fout(fileName);  //打开一个文件准备写入,如果文件不存在则创建,存在则先清空再准备写入;
	fout << “This line written directly to the file...\n”;//写入字符串
	cin.getline(buffer,255);  //
	fout << buffer << “\n”;   //写入输入的字符串,fout是文件名
	fout.close();  //关闭文件

	ifstream fin(fileName); //打开文件,进行读取,fin也是文件名
	char ch;
	while (fin.get(ch))//从文件中一个个读取
		cout << ch;
	fin.close();  //关闭文件
	return 0;
}

执行结果如下:

chen hua ping
This line written directly to the file...
chen hua ping
请按任意键继续. . .

打开file.txt文件,内容如下:

This line written directly to the file...
chen hua ping

17.5.1 利用ofstream打开文件,修改默认行为

默认行为是如果文件不存在就创建它,如果文件存在则清空文件;

  • ios::app:附加到已有文件末尾,而不是清楚他们;即追加内容;
  • ios::ate:处于文件末尾,但是可以在文件中任何地方写入数据;
  • ios::trunc:默认行为,清空已有文件内容;
  • ios::nocreate:如果文件不存在,则打开操作失败;
  • ios::nocreplase:如果文件已经存在,则打开操作失败
  • 建议1:每次打开文件时,需测试确认文件已经成功打开;
  • 建议2:重用现有的ifstream和ofstream;
  • 建议3:用完fstream对象时要关闭;

准备一个file.txt文件,内容如下:

file content
current content
est content
est content

chen hua ping

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

int main() 
{
	char fileName[] = "file.txt";
	char buffer[255];

	ifstream fin(fileName);
	if (fin){
		//cout << "Current file contents:\n";
		char ch;
		while (fin.get(ch))
			cout << ch;
		//cout << "\n***End of file contents.***\n";
	}
	fin.close();

	ofstream fout(fileName,ios::app);
	if (!fout){
		cout << "Unable to open " << fileName << " for appending.\n";
		return(1);
	}
	cin.getline(buffer,255);
	fout << buffer << "\n";
	fout.close();

	ifstream fin1(fileName);
	if (!fin1){
		cout << "Unable to open " << fileName << " for reading.\n";
		return(1);
	}
	//cout << "\nHere's the contents of the file:\n";
	char ch;
	while (fin1.get(ch))
		cout << ch;
	//cout << "\n***End of file contents.***\n";
	fin1.close();
	return 0;
}

执行结果如下:

file content
current content
est content
est content

chen hua ping

dddddddddddddddddddd

17.6 命令行处理

通过命令行启动程序并传入参数:vint main(intagrc, char **argv)

  • argc传入参数数;
  • argv是参数内容,argv[0]表示程序名,argv[1]第一个参数;
#include <iostream>
int main(int argc, char **argv)
{
	std::cout << "Received " << argc << " arguments...\n";
	for (int i=0; i<argc; i++)
		std::cout << "argument " << i << ": " << argv[i] << std::endl;
	return 0;
}

执行结果如下:

Received 1 arguments...
argument 0: e:\train\source\C++\17014_argc\Debug\17014_argc.exe
请按任意键继续. . .

通过命令行之行:E:\train\source\C++\17014_argc\Debug\17014_argc param1 parma2 param3 param4 param5

C:\Users\Administrator>E:\train\source\C++\17014_argc\Debug\17014_argc param1 parma2 param3 param4 param5
Received 6 arguments...
argument 0: E:\train\source\C++\17014_argc\Debug\17014_argc
argument 1: param1
argument 2: parma2
argument 3: param3
argument 4: param4
argument 5: param5

C:\Users\Administrator>

发表回复