我一直在尝试使用 getline 来识别我的字符串输入中的空格。数字不是空格,而是在单词之间插入的特殊字符。当我正常使用 cin 时,该功能有效,但看不到空格。
如何更改以下内容以便有实际空间?
这是我的 getline 代码(字符串中的字母不再移动):
#include "stdafx.h"
using namespace std;
#include <iostream>
#include <string>
void encrypt(std::string &iostr, int key)
{
key %= 26;
int ch;
for (auto &it : iostr)
{
ch = tolower(it) + key;
if (ch > 'z')
ch -= 26;
it = ch;
}
}
int main()
{
string source;
int key = 1;
cout << "Paste cyphertext and press enter to shift 1 right: ";
getline(cin, source);
encrypt(source, key);
cout << source << "";
system("pause");
return 0;
}
最佳答案
encrypt
插入特殊字符的原因是循环不注意空格,将它们按 key
代码点移动,其方式与循环相同常规字符。
添加检查字符是否为小写字母将解决问题:
for (auto &it : iostr)
{
ch = tolower(it);
if (!islower(ch)) {
continue;
}
ch += key;
if (ch > 'z') {
ch -= 26;
}
it = ch;
}
关于c++ - 为什么要在空格中插入数字和特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30626644/