【和春笋一起学C++】文本输入与读取(二)

发布于:2025-02-10 ⋅ 阅读:(30) ⋅ 点赞:(0)

目录

使用cin.eof()或cin.fail()检测EOF

使用cin.get(ch)的返回结果检测EOF

使用cin.get()的返回结果检测EOF


上篇文章《文本输入与读取》学习了遇到某个字符时停止读取,那如果要读取键盘输入的所有字符该怎么做呢。答案是检测文件尾(EOF)。很多操作系统都支持通过键盘模拟文件尾条件,Unix通过Ctrl+D实现,windows系统通过Ctrl+Z实现。

使用cin.eof()或cin.fail()检测EOF

使用cin读取输入文本时,当遇到EOF后,cin将两位(eofbit和failbit)都设置为1。可以通过成员函数eof()来查看eofbit是否被设置。如果检测到EOF,则cin.eof()将返回bool值为true,否则返回false。

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

int main()
{
	int count = 0;
	cout << "Enter characters, enter # to quit: \n";
	char ch;
	cin.get(ch);
	while (cin.eof()==false)
	{
		cout << ch;
		count++;
		cin.get(ch);
	}
	cout << endl << count << " characters read\n";
	return 0;
}

while循环语句的检测条件也可以使用cin.fail() ,效果是一样的。

while (cin.fail()==false)
	{
		cout << ch;
		count++;
		cin.get(ch);
	}

程序输出结果如下,因为是使用键盘作为输入文本,所以需要通过Ctrl+Z来模拟EOF。 

使用cin.get(ch)的返回结果检测EOF

上篇文章《文本输入与读取》中提到:

cin.get(ch)的返回值是cin对象,istream类提供了一个可以将istream类的对象(如cin)转化为bool值的函数,当cin对象出现在需要bool值的地方(如在while循环的测试条件中,if条件语句的条件判断中)时,该转换函数将被调用。

当到达EOF时,cin.get(ch)的返回值执行bool转换后值为false。当正常读取字符,未到达EOF时,cin.get(ch)的返回值执行bool转换后值为true。所以,while循环语句中的检测条件可以直接使用cin.get(ch)来检测EOF。代码如下:

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

int main()
{
	int count = 0;
	cout << "Enter characters, enter # to quit: \n";
	char ch;
	while (cin.get(ch))
	{
		cout << ch;
		count++;
	}
	cout << endl << count << " characters read\n";
	return 0;
}

程序分析:为判断循环测试条件,程序必须首先调用cin.get(ch)。如果成功,则将值放入ch中。然后,程序获得函数调用的返回值,即cin。最后,程序对cin进行bool转换,如果输入成功,则结果为true,否则为false。

另一方面,使用cin.get(ch)进行输入时,将不会导致任何类型方面的问题。cin.get(char)函数在到达EOF时,不会将一个特殊值赋给ch。在这种情况下,它不会将任何值赋给ch。ch不会被用来存储非char值。

使用cin.get()的返回结果检测EOF

上篇文章《文本输入与读取》中提到,当到达EOF时,cin.get()的返回值就是EOF。注意,此处的EOF不表示输入中的字符,而是指出没有字符。

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

int main()
{
	int count = 0;
	cout << "Enter characters, enter # to quit: \n";
	char ch;
	ch = cin.get();
	while (ch != EOF)
	{
		cout << ch;
		count++;
		ch = cin.get();
	}
	cout << endl << count << " characters read\n";
	return 0;
}

程序分析:如果ch是一个 字符,则循环将显示它。如果ch为EOF,则循环将结束。


网站公告

今日签到

点亮在社区的每一天
去签到