我正在为我的 CS2400 类(class)编写一个程序作为家庭作业,我们将在其中加密消息、解密消息或让用户退出。
我从设置函数开始,没有在定义中写太多。
到目前为止,这是我的代码。
#include <iostream>
#include <iomanip>
using namespace std;
void encryption (char message[]);//prototype
void decryption (char message[]);//prototype
int main(){
int ans=0;
char message[100];
while (ans!=3){
cout << "1. Encrypt a message.\n2. Decrypt a message.\n3. Quit\n";
cin >> ans;
if (ans==1){
encryption (message);
}
if (ans==2){
decryption (message);
}
if (ans==3){
break;
}
}
return 0;
}
void encryption (char message[]){
int count=0;
cout << "Please enter a message to be encrypted:\n\n";
cin.get(message[count]);
while (message[count]!='\n'){
count++;
cin.get(message[count]);
}
}
void decryption (char message[]){
int count=0;
cout << "Please enter a message to be decrypted:\n\n";
cin.get(message[count]);
while (message[count]!='\n'){
count++;
cin.get(message[count]);
}
}
When run, it lets me choose an option of the three, but when choosing encrypt or decrypt, it prints the statement asking for input then makes me choose again without giving me a chance to input anything.
关于为什么它不会给我输入任何内容的机会的任何想法?
最佳答案
问题是 cin >> ans
不使用 Enter 按键(换行符)。因此,当您继续调用 cin.get()
时,返回的第一个字符是上一行中的 Enter 按键。
一个更好的主意是使用 std::getline
对于所有 用户输入。这样做可以避免这个问题。
关于C++使用转置密码加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272796/