逐字符读取文件或键盘文本

1、使用cin

 1 #include <iostream>
 2 using namespace std;
 3 int main(){
 4     char ch;
 5     int count = 0;
 6     cout <<"Enter charactes;enter # to-quit:\n";
 7     cin >> ch;
 8     while (ch!='#'){
 9         cout <<ch;// echo the character
10         ++count;//count the character
11         cin(ch);// get the next character
12     }
13     cout << endl << count <<  " characters read\n";
14     return 0;
15 }

缺点:cin在读取char时和读取其他基本类型一样,将忽略空格和换行符;发送给cin的输入被缓冲,只有回车,输入才会被发送给程序。

2、使用cin.get(char)读取输入中的字符

3、文件尾(EFO)条件

  当使用文件作为输入流时,为了确保适时结束文件读取操作,采用检查文件尾判断程序该何时停止读取

检测到EFO后,cin.eof()

posted @ 2018-08-26 08:11  xymys  阅读(166)  评论(0编辑  收藏  举报