C++ 文本输入函数的区别

cin >> ch;  // 将忽略空格和换行符,发送给cin的输入将缓冲,只有在用户按下回车键后,输入的内容才会被发送给程序.

cin.get(ch); // 不会互虐忽略任何字符,但是输入仍会被缓冲.

ch = cin.get();  // 类似C语言的 getchar() 函数.可以搭配 cin.put(ch) 函数使用.

 

建议使用 cin.get() 或 类似C语言的 ch = cin.get()

 

cin >> ch 实例:

代码:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 
 4 int main()
 5 {
 6     using namespace std;
 7 
 8     cout << "Start input.if you input # means quit.\n";
 9 
10     int count;
11     char ch;
12     cin >> ch;
13 
14     while( ch != '#' )
15     {
16         cout << ch;
17         ++count;
18         cin >> ch;
19     }
20 
21     cout << "\nYou input :" << count << " chars\n";
22 
23     system("pause");
24     return 0;
25 }
View Code

运行结果:

 

 

cin.get(ch) 实例

 1 #include <iostream>
 2 #include <stdlib.h>
 3 
 4 int main( )
 5 {
 6     using namespace std;
 7 
 8     char ch;
 9     int count;
10 
11     cout << "Enter string:" << endl;
12 
13     while( cin.get(ch) )
14     {
15         cout << ch;
16         ++count;
17     }
18 
19 
20     cout << endl << endl << "You input :" << count << "chars\n";
21 
22     system("pause");
23     return 0;
24 }
View Code

运行结果

:

ch = cin.get()

代码:

 1 #include <iostream>
 2 #include <stdlib.h>
 3 
 4 int main()
 5 {
 6     using namespace std;
 7 
 8     char ch;
 9     int count;
10 
11     while( (ch = cin.get() ) != EOF )
12     {
13         cout << ch;
14         ++count;
15     }
16 
17     cout << endl << endl << "You input : " << count << " chars" << endl;
18 
19 
20     system("pause");
21     return 0;
22 }
View Code

运行结果:

posted @ 2015-05-12 18:59  Lone_thinker  阅读(109)  评论(0)    收藏  举报