①选择一个特殊字符作为结束字符,有时候被称为哨兵字符。
#include <iostream>
using namespace std;
int main()
{
char ch;
int count = 0;
cout << "Enter characters, enter # to quit: " << endl;
cin >> ch; //读取输入的字符,并赋给ch,但是不能读取空格
while(ch != '#') //选择#作为结束字符
{
cout << ch;
count++;
cin >> ch;
}
cout << endl << count << "characters read" << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
char ch;
int count = 0;
cout << "Enter characters, enter # to quie: " << endl;
cin.get(ch); //读取输入的字符,并赋值给ch,可以读取空格
while(ch != '#') //选择#作为结束字符
{
cout << ch;
count++;
cin.get(ch);
}
cout << endl << count << " characters read" << endl;
return 0;
}
②使用文件尾条件:
当检测到文件尾EOF时,则eofbit和failbit都被设置为1,可以通过成员函数eof()来查看eofbit是否被设置,cin.eof()将返回true,cin.fail()也返回true
使用EOF检测文件尾实例:
使用EOF需要包含cstdio这个头文件
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char ch;
int count = 0;
cout << "Enter characters:" << endl;
ch = cin.get();
while(ch != EOF)
{
cout.put(ch);
count++;
ch = cin.get();
}
cout << count << " characters read!" << endl;
return 0;
}