bluesky5210 发表于 2014-11-15 21:40:38

C++的输入流如何提取字符并屏蔽其他多余的字符??

bool accept()
{
        int tries =0 ;
        while( tries<4 )
        {
                cout<<"Do you want to accept (y/n)?\n";
                char answer = 0;
                //cin>>answer;
                cin.get(answer);//这里如果用户输入多个字符后,程序就一下子结束了
                switch(answer)   //现在只需要提取cin的第一个字符,之后的字符如何屏蔽呢??
                {
                case 'y': cout<<"you enter y"<<endl;
                                return true;
                                break;
                case 'n': cout<<"you enter n"<<endl;
                                return false;
                                break;
                default: cout<<"I don't understand that.\n";
                                //ungetc(answer,stdin);
                                tries+=1;
                }
        }
        cout<<"Please enter y or n .\n";
        return false;
}

bluesky5210 发表于 2014-11-15 22:13:18

bool accept()
{
         int tries =0 ;
         while( tries<4 )
         {
               cout<<"Do you want to accept (y/n)?\n";
        string answer;
        cin>>answer;
        switch(answer)
                {
               case 'y': cout<<"you enter y"<<endl;
                                 return true;
                                 break;
               case 'n': cout<<"you enter n"<<endl;
                                 return false;
                                 break;
               default: cout<<"I don't understand that.\n";
                                 //ungetc(answer,stdin);
                                 tries+=1;
               }
         }
         cout<<"Please enter y or n .\n";
         return false;
}

fliou1 发表于 2014-11-15 22:43:04

你输入小于4个字符就不会退出 程序的退出在while循环那里

fliou1 发表于 2014-11-15 23:00:38

#include <iostream>

using namespace std;

int main(int argc,char *argv[])
{
        bool tries=false ;
      while( !tries)
      {
                cout<<"Do you want to accept (y/n)?\n";
                char answer = 0;
                //cin>>answer;
                cin.get(answer);//这里如果用户输入多个字符后,程序就一下子结束了
                                cin.clear();
                                cin.ignore(1000,'\n');

                switch(answer)   //现在只需要提取cin的第一个字符,之后的字符如何屏蔽呢??
                {
                case 'y': cout<<"you enter y"<<endl;
                              return true;
                              break;
                case 'n': cout<<"you enter n"<<endl;
                              return false;
                              break;
                default: cout<<"I don't understand that.\n";
                              //ungetc(answer,stdin);
                              
                }
      }
      cout<<"Please enter y or n .\n";
      return false;
}
页: [1]
查看完整版本: C++的输入流如何提取字符并屏蔽其他多余的字符??