LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 706|回复: 1

cin.get()的问题。

[复制链接]
发表于 2003-9-23 23:49:21 | 显示全部楼层 |阅读模式
我预先设定了一个数组char result[]="Best regards", 让用户猜,
然后用cin.get()接收用户输入,并用用户输入的内容组成一个新的数组input [11],
然后逐个比较用户输入的每个字符。
我设置了循环结构,使用户可以试多次,第一次输入Best regards,程序认为用户输入正确,第二次输入相同的内容,程序却认为错误,为什么?

  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4. const int size = 11;
  5. void min ();
  6. void try_again ();
  7. int main () {
  8.   cout << "First, please let me say: best regards to you."
  9.     <<
  10.     "The program is run to guess a clase that conains eleven letter. Only the first one is capital."
  11.     << "You could type eleven letters followed by enter." <<
  12.     "Okay, now, give it a go->:" << endl;
  13.   min ();
  14. }

  15. void min () {
  16.   char input[size];
  17.   char result[] = "Best regards";
  18.   char c;
  19.   cout << "looping ";
  20.   for (int i = 0; i < size; i++)        //initialize the array
  21.     cin.get (input[i]);
  22.   for (int i = 0; i < size; i++)        //compare with the result
  23.     if (input[i] == result[i])
  24.       cout << "The " << i << "th letter is good." << endl;
  25.     else
  26.       cout << "Sorry for the " << i << "th letter." << endl;
  27.   cin.ignore ();                //the cin is used to filter extra letters
  28.   cout << "Do you want ot try again, yet? y for yes, n for no." << endl;
  29.   try_again ();
  30. }

  31. void try_again () {
  32.   char s;
  33.   cin >> s;                     //the cin is used to filter extra letters
  34.   if (s == 'y')
  35.     min ();
  36.   else if (s == 'n')
  37.     exit (0);
  38.   else
  39.     {
  40.       cout << "Please enter y, or n:";
  41.       try_again ();
  42.     }
  43. }
复制代码
 楼主| 发表于 2003-9-23 23:57:57 | 显示全部楼层
void try_again () {
  char s;
  cin >> s;   
在这后边加上cin.ignore();
好了。
刚才别人告诉的,不是自己想到的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表