while循环为什么不再次使用输入字符串?

时间:2019-12-30 21:50:11

标签: c++

我用C ++为Ceaser cypher编写了以下代码。我在这里使用while循环enter code here,因为当用户加密/解密消息时,应该有一个循环来再次尝试。但是,当我运行代码时,对于第一次迭代,它工作得很好,但是当第二次运行时,它不使用输入字符串。 这是我的代码

#include <conio.h>
#include <stdio.h>

#include <iostream>

using namespace std;

int main() {
  char x = 'y';
  int k, option;
  string msg;
  string encrypt;
  string decrypt;

  while (x != 'n')  // run until user selects n
  {
    cout << "Please enter your message: ";
    getline(cin, msg);  // gets input message

    cout << "\nEnter number for the key between 1-25: ";
    cin >> k;

    while (k < 1 || k > 25) {
      cout << "\nPlease select valid key between 1 and 25 ";
      cin >> k;
    }

    cout << "\nSelect option: "
         << "\n1 for Encrypt "
         << "\n2 for Decrypt "
         << "\n";
    cin >> option;
    while (option != 1 && option != 2) {
      cout << "\nSorry wrong option. Please select again\n ";
      cin >> option;
    }

    switch (option) {
      case 1:  // for encryption
        for (int i = 0; i < msg.length(); i++) {
          if (isalpha(msg[i])) {
            if (islower(msg[i])) {
              encrypt[i] = (((msg[i] - 97) + k) % 26) + 97;
              cout << encrypt[i];
            }
          }
          if (isupper(msg[i])) {
            encrypt[i] = (((msg[i] - 65) + k) % 26) + 65;
            cout << encrypt[i];
          }
        }
        break;

      case 2:  // for decryption

        for (int i = 0; i < msg.length(); i++) {
          if (islower(msg[i])) {
            decrypt[i] = ((((msg[i] - 97) - k) + 26) % 26) + 97;
            cout << decrypt[i];
          }
          if (isupper(msg[i])) {
            decrypt[i] = ((((msg[i] - 97) - k) + 26) % 26) + 97;
            cout << decrypt[i];
          }
        }
        break;
    }
    cout << "\nDo you want to try again?(Y/N) ";  // asking user if he wants to
                                                  // encrypt or decrypt again
    cin >> x;
  }
}

2 个答案:

答案 0 :(得分:0)

#include <string>

将其更改为此:

getline(cin, msg);  // gets input message
if (msg == "") getline(cin, msg);

此外,您无法处理未初始化的字符串...

encrypt[i] = ...encrypt += ...

decrypt[i] = ...decrypt += ...

第二解密是重复的,将其更改为:

decrypt += ((((msg[i] - 65) - k) + 26) % 26) + 65;

答案 1 :(得分:0)

您需要在cin >> x之后立即在代码末尾刷新缓冲区。这是做到这一点的方法之一

...                                         

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');`

也不要忘记为数字限制添加#include <limits>

这是您可能会发现有帮助的帖子How do I flush the cin buffer?

已更新:正如我在评论部分中所纠正的,cin.clear();仅在错误的输入在流中设置错误标志时才是必需的。