5.5,5.6

5.5循环和文本输入

使用cin进行输入

 1 #include<iostream>
 2 int main()
 3 {
 4     using namespace std;
 5     char ch;
 6     int count=0;
 7     cout<<"enter the characters,enter #to quit";
 8     cin>>ch;
 9     while(ch!='#')
10     {
11         cout<<ch;
12         count++;
13         cin>>ch;
14     }
15     cout<<endl<<count<<" characters read";
16     return 0;
17 }

程序输入字符,以#作为结束标记,并统计#之前的字符数。

cin将忽略空格和换行符,因此并没有统计和显示空格。

 

使用cin.get(ch) 读取输入的下一个字符,即使是空格,并将其赋给变量ch。

 1 #include<iostream>
 2 int main()
 3 {
 4     using namespace std;
 5     char ch;
 6     int count=0;
 7     cout<<"enter the characters,enter #to quit";
 8     cin.get(ch);
 9     while(ch!='#')
10     {
11         cout<<ch;
12         count++;
13         cin.get(ch);
14     }
15     cout<<endl<<count<<" characters read";
16     return 0;
17 }

文件尾条件:检测文件尾(EOF)

成员函数eof()和fail()

ctrl+z表示结束。

 1 #include<iostream>
 2 int main()
 3 {
 4     using namespace std;
 5     char ch;
 6     int count=0;
 7     cout<<"enter the characters,enter #to quit";
 8     cin.get(ch);
 9     while(cin.fail()==false)
10     {
11         cout<<ch;
12         count++;
13         cin.get(ch);
14     }
15     cout<<endl<<count<<" characters read";
16     return 0;
17 }

cin.clear()可以清楚EOF标记,使输入继续进行。

原文地址:https://www.cnblogs.com/taoxiuxia/p/4143232.html