使用原始的cin进行输入
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin >> ch;//在程序开始之前读取第一个字符,这样循环可以测试第一个字符,因为第一个字符可能就是#
while (ch != '#')
//使用原始的cin进行输入,停止读取的方法时选择一个哨兵字符(此处是#)将其作为停止标记
{
cout << ch;
++count;
cin >> ch;
}
cout << endl << count << " characters read\n";
return 0;
}
Enter characters; enter # to quit:
see you again#hello//发送给cin的输入被缓冲,也就是只有用户按下回车键时,
输入的内容才会被发送给程序,所以这里输入#后依然能输入字符。
按下回车后,这整个字符序列将会被发送给程序,但是程序在遇到#后将结束对输入的处理。
seeyouagain//程序输入时忽略了空格,原因是读取char值时,与读取其他类型一样,
cin将忽略空格和换行符。因此输入的空格没有被回显,也没有被包含在计数内。
11 characters read
使用cin.get(char)进行补救
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch);
//成员函数cin.get()读取输入的下一个字符,即便它是空格,制表符或者是换行符,并将其赋值给ch。
while (ch != '#')
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read\n";
return 0;
}
Enter characters; enter # to quit:
yang guo#sndo
yang guo
8 characters read//这个程序回显了每个字符,并将全部字符计算在内,其中包含空格。但是输入仍被缓冲。
使用哪一个cin.get()
#include <iostream>
int main()
{
using namespace std;
int ArSize;
char name[ArSize];
cout << "Enter your name:\n";
cin.get(name, ArSize);
//这里一共接收两个参数。第一个参数就是字符串(char*类型)的地址(数组名是其第一个元素的地址)和int整型的整数;
cin.get();
//由于函数重载的原因(函数重载可以创建多个同名函数,条件是参数列表不同),
//例如:在c++中使用cin.get(name,ArSize),则编译器就找到char*和int作为参数的cin.get()版本;
//如果使用cin.get(ch)版本,则编译器将使用接受一个char参数的版本,
//如果没有提供参数,则编译器将使用不接受任何参数的cin.get()版本。
return 0;
}
Enter your name:
yang guo
文件尾条件
文件尾条件:很多操作系统很多都允许通过键盘来模拟文件尾条件,在windoes中一般就是ctrl+zh和Enter。c++支持这样的条件,即使底层操作系统不支持。如果在编程环境汇总能够检测到EOF,则可以使用键盘输入,并在键盘输入模拟EOF。
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch);
while (cin.fail() == false)//fail()和eof()方法报告最近读取的结果,也就是说他是时候报告,而不是预先报告。
//所以应该将cin.eof()或cin.fail()测试放在读取后。这里使用的是fail()因为fail()可用于更多的实现中。
//检测到EOF后,将两位eofbit和failbit都设置成1,可以通过成员函数eof()来查看ecobit是否被设置;
//如果检测到EOF,则cin.eof()将返回true,否则返回false;同样,如果eofbit()和failbit()被设置成1,
//则fail()成员函数返回true,否则返回false。
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read\n";
return 0;
}
The green bird sings in the winter.//输入后键入enter
The green bird sings in the winter.
yes, but the crow files in the dawn.//输入后键入enter
yes, but the crow files in the dawn.
^Z //输入ctrl+z后enter (模仿EOF条件)
73 characters read
EOF结束输入
cin方法检测到EOF时,将设置cin对象中一个指示EOF条件的标记。设置这个标记后,cin将不在读取输入,再次调用cin也不管用。
对于文件输入,程序不能读取超出文件尾的内容。但是,对于键盘输入,有可能使用模拟EOF来结束循环,但是稍后要读取其他输入。此时使用cin.clear()方法可以清除EOF标记,是输入继续进行。但是在有些系统中,按ctrl+z实际上将结束输入和输出,而cin.clear()将无法恢复输入和输出。