切换语句不允许第一个用户输入

时间:2014-06-26 07:16:24

标签: c++ switch-statement getline

此函数检查二维char数组并使用大小遍历数组中的每个单词,搜索>,这将把它带入搜索案例的switch语句。

我在switch语句中遇到问题,特别是在switch语句第一次通过default的情况下用户输入。

void parseWord(char story[][256], int size)
{
   for (int i = 0; i < size; i++)
   {
      char prompt[256][32];
      if (story[i][0] == '<')
      {
         switch (story[i][1])
         {
            case '#':
               story[i][0] = '\n';
               story[i][1] = 0;
               break;
            case '{':
               story[i][0] = ' ';
               story[i][1] = '\"';
               story[i][2] = 0;
               break;
            case '}':
               story[i][0] = '\"';
               story[i][1] = ' ';
               story[i][2] = 0;
               break;
            case '[':
               story[i][0] = ' ';
               story[i][1] = '\'';
               story[i][2] = 0;
               break;
            case ']':
               story[i][0] = '\'';
               story[i][1] = ' ';
               story[i][2] = 0;
               break;
            default:
               int p = 1;

               prompt[i][0] = (char)(toupper(story[i][1]));
               for (int j = 2; story[i][j] != '>'; j++)
               {
                  if (story[i][j] == '_')
                     prompt[i][p] = ' ';
                  else
                     prompt[i][p] = story[i][j];
                  p++;
               }

               cout << '\t' << prompt[i] << ": ";

               cin.getline(prompt[i], 32);

               int z = 0;
               for (int t=0; prompt[i][t] != '\0'; t++)
               {
                  story[i][t] = prompt[i][t];
                  z++;
               }

               story[i][z] = 0;


         }
      }
   }

   return;
}

cin.getline(prompt[i], 32);第一次运行时出现问题。

这是我在运行我的函数时获得的输出,用户输入在*:s:

 Web site name:  Verb: *run*
 Plural noun: *dogs*
 Plural noun: *cats*
 Proper noun: *Jimmy*
 Adjective: *smart*
 Noun: *table*
 Noun: *desk*
 Boolean operator: *xor*
 Noun: *shoe*
 Favorite website: *google.com*
 Another website: *yahoo.com*
 Adjective: *cold*
 Emoticon: *:P*

如您所见,代码运行时会跳过cin.getline(prompt[i], 32),并立即转到下一个提示并请求用户输入。这不会使Verb中输入的内容等于Web site name应该是什么,但不允许将任何内容输入Web site name并使其为空。 Verb仍然等于,在这种情况下是“run”。

为什么switch语句似乎第一次跳过cin.getline(prompt[i], 32)语句? default案例在第一个似乎按预期工作之后运行的所有时间我无法看到或理解为什么第一次在default案例中运行时不允许用户输入开关。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我发现在我的程序中的其他函数中,我收到了cin的输入。看Why getline skips first line?我看到cincin.getline()不能很好地协同工作。在尝试cin.ignore()语句(修复此问题但创建了许多其他语句)后,我决定使用cin.getline()专门获取所有输入。所有输入现在都有效。

相关问题