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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值