c++ - 为什么我的代码在 getline(cin, *userInput) 中不接受空格?
问题描述
我正在尝试使用 rot13 方法获取用户输入、编码或解码,然后使用编码/解码的文本显示用户输入。
我不确定该尝试什么,因为使用 rot13 方法进行编码/解码的算法是由我的教授提供的。我认为这与它有关,但我不确定从哪里开始。
我尝试过使用cin >> *userInput
,但是当输入带有空格的字符串时,空格仍然没有出现。
例如,当我投入时hello world
,我得到uryybjbeyq
回报。一点空间都没有。
#include <iostream>
#include <string>
using namespace std;
string encrypt(string input) {
int inputSize = input.size();
int index = 0;
while (index != inputSize) {
if (input[index] >= 97 && input[index] <= 109)
input[index] = input[index] + 13;
else if (input[index] >= 110 && input[index] <= 122)
input[index] = input[index] - 13;
else if(input[index] >= 65 && input[index] <= 77)
input[index] = input[index] + 13;
else if(input[index] <= 78 && input[index] <= 90)
input[index] = input[index] - 13;
index++;
}
return input;
}
int main() {
bool prog = true;
char ans;
char ans1;
string* userInput;
string* cypher;
cypher = new string;
userInput = new string;
do {
cout << "Do you want to encode or decode a message? Y/N" << endl;
cin >> ans;
if (ans == 'y' || ans =='Y') {
prog = true;
} else if(ans == 'N' || ans == 'n') {
break;
}
cout << "OK, do you want encode or decode? E/D" << endl;
cin >> ans1;
if (ans1 == 'e' || ans1 == 'E') {
cout << "What is the message you want to encode?" << endl;
cin.ignore();
getline(cin, *userInput);
*cypher = encrypt(*userInput);
cout << *cypher << endl;
delete userInput;
delete cypher;
cypher = nullptr;
userInput = nullptr;
}
if (ans1 == 'd' || ans1 == 'D') {
cout << "What is the message you want to decode?" << endl;
cin.ignore();
getline(cin, *userInput);
*cypher = encrypt(*userInput);
cout << *cypher << endl;
delete userInput;
delete cypher;
cypher = nullptr;
userInput = nullptr;
}
} while (prog == true);
cout << "Goodbye." << endl;
return 0;
}
帮助将不胜感激,谢谢。
解决方案
else if(input[index] <= 78 && input[index] <= 90)
input[index] = input[index] - 13;
该条件格式错误,因为它应该检查 78 到 90 之间的字符。
else if(input[index] >= 78 && input[index] <= 90)
input[index] = input[index] - 13;
这将提供所需的输出。
此外,您不需要在此处使用指针。string userInput;
对于这个程序来说已经足够了,你可以摆脱所有的new
anddelete
和nullptr
分配。
推荐阅读
- swift - Picker inside of form no longer selecting
- angular - wefontloader 通过显示 `ReferenceError: window is not defined` 破坏了构建 ssr
- deep-learning - 如何使用 cudnnActivationBackward
- c# - 根据该信息获取要删除的单个文件
- recursion - Ocaml 列表递归
- asp.net-core - 获取 API 的 URI
- javascript - js函数内部的push()返回未定义
- python-3.x - Python 中的 Twitter API v2 - 日期时间转换问题
- asp.net-core - devops nuget 无法找到 microsoft.graph.auth 预览
- gimp - 保存带有透明边框的PNG