输入字符串不会正确输出(输入字符变量)

  • 本文关键字:输出 字符变量 字符串 c++
  • 更新时间 :
  • 英文 :


我正在编写凯撒密码编码器/解码器。我遵循特定的指导原则,包括选择编码或解码。用于编码或解码的变量必须是一个字符;e"d"E"D";或";编码"解码";。任何以";e、 e〃;或";d、 d";是可以接受的。

输入字符串";编码";将不再允许在我的代码中输入。输入单个字符有效。

#include <iostream>
#include <string>
using namespace std;
int main() {
int shift = 0;
char inChoice;
cout << "Do you wish to encode or decode?" << endl;
cout << "(Type "e" to encode, or "d" to decode): ";
cin >> inChoice;
if (inChoice == 'e' || inChoice == 'E')
{
cout << "How many characters to shift?" << endl;
cout << "(Enter a positive integer): ";
cin >> shift;
while (shift < 0){
cout << "You must enter a positive integer: ";
cin >> shift;
}
}
else
{
cout << "You must either enter "e" or "d": ";
cin >> inChoice;
}
return 0;
}

输出将返回,就好像我输入了"0";e";当提示我是否希望编码或解码时,将其转换为输入流。然后它会要求按键移位,然后不允许任何进一步的输入,只需停止程序。

inChoice是一个char,因此当您读取用户输入时,它只会使用第一个字符。如果用户输入了Encode,则inChoice将包含'E',但输入的其余部分仍在等待读取。当您获得shift的输入时,cin将看到最后一个输入的结束位置,并尝试将ncode转换为整数。

cin >> shift;  // looks at the end of the last input: "ncode"

尝试将选择读取到string而不是char中,并查看第一个字符:

// ...
std::string inChoice;
cout << "Do you wish to encode or decode?" << endl;
cout << "(Type "e" to encode, or "d" to decode): ";
cin >> inChoice;
if (inChoice[0] == 'e' || inChoice[0] == 'E')
{
// ...

您需要将inChoice声明为std::string,而不是char,因为这是从标准输入(字符串(进入程序的内容。

最新更新