cin 和 getchar()



1 #include <stdio.h>
  2 #include <iostream>
  3 #include <string.h>
  4 using namespace std;
  5
  6 int main()
  7 {
  8     char buffer[200];
  9     int i=0;                                                               
 10     char temp;
 11     temp = getchar();
 12     if(temp == '\n')
 13         return 0;
 14     while(temp == ' ')
 15     {
 16         temp= getchar();
 17         if(temp != ' ')
 18             break;
 19     };      
 20     if(temp != '\n')
 21     {
 22         while(temp != '\n')
 23         {
 24             buffer[i++] = temp;
 25             temp = getchar();
 26             if(temp == ' ')
 27             {
 28                 while (temp == ' ')
 29                     temp = getchar();
 30                 buffer[i++] = ' ';
 31             }
 32         }
 33     }
 34
 35 //  cout << endl << buffer;
 36     for(int j=0; j<strlen(buffer); j++)
 37         cout << buffer[j];
 38     cout << endl;
 39     return 0;
 40 }          
 运行结果:
     today is     nice day. hl

today is nice day. hl
关键点:
1. do while和while运行顺序要保证正确
2. temp = getchar()为正确,而cin >> temp无法正确实现功能

cin>>

该操作符是根据后面变量的类型读取数据。

输入结束条件 :遇到Enter、Space、Tab键。

对结束符的处理 :丢弃缓冲区中使得输入结束的结束符(Enter、Space、Tab)

请参考如下网址:

http://www.cnblogs.com/A-Song/archive/2012/01/29/2331204.html


猜你喜欢

转载自blog.csdn.net/zhang_fei_fresh/article/details/49895961