c++ - 为什么要在空格中插入数字和特殊字符?

标签 c++ input getline

我一直在尝试使用 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/

相关文章:

c++ - Boost.flyweight 和 Boost.MPL

C++ 模板 : Inlined code and Compiler Optimzations

c - 尽管导入了 stdio,但 getline 未在此范围内声明

c++ - 在 C++ 中使用多个 getline 实例

c++ - 模板类的工厂方法

c++ - C++11 chrono 有哪些替代方案?

c - 如何将 int 和 double 作为输入而不是 char?

java - 如何检查用户输入之前是否输入过?

python - 如何将两个大小未知的相关输入与变量链接起来

c++ - getline() 不打开文本文件