c++ - 为什么第二个 'cin >>' 不会被处理?

标签 c++ api cryptography iostream cin

初学C++,去年学了Java,马上这个学期又要学C++密码学编程和MFC/API之类的东西,现在比较迷茫,总之请看代码:

#include <iostream>
#include <string>

using namespace std;

#define strSize 100

int main()
{
    char message[strSize];
    char cipher[strSize];
    char plaintext[strSize];
    int nCount;
    char nEKey, nDKey;

    for(int i=0; i<strSize; ++i)
    {
        message[i] = '\0';
        cipher[i] = '\0';
        plaintext[i] = '\0';
    }

    cout << "Please enter your confidential message:" << endl;
    cin.getline(message, strSize);
    nCount = cin.gcount();
    cout << nCount << " characters read." << endl;

    cout << "Enter secret key:" << endl;
    cin >> nEKey;
    for(int j=0; j<nCount-1; ++j)
        cipher[j] = message[j] + nEKey;
    cout << "Message is encrypted into:" << endl << cipher << endl << endl;

    cout << "Type your secret key again:" << endl;
    cin >> nDKey;

    for (int k=0; k<nCount-1; ++k)
        plaintext[k] = cipher[k] - nDKey;
    cout << "Cipher text is decrypted to:" << endl << plaintext << endl;

    return 0;
}

运行编译后的程序,结果为:

Please enter your confidential message:
hello world
12 characters read.
Enter secret key:
abc
Message is encrypted into:
袴?望答

Type your secret key again:
Cipher text is decrypted to:
gdkknvnqkc

我都用 g++ 和 visual studio 编译了它,它们产生了相同的输出。

现在我的问题是:为什么不处理第二个 cin?

在 visual studio 中它给了我一个警告说:

...\enc.cpp(25): warning C4244: '=' : conversion from 'std::streamsize' to 'int', possible loss of data

OMD,我是新手,不知道是什么意思,谁能帮忙修一下?

非常感谢!

最佳答案

nEKeynDKey 都是char类型,也就是说它们只能存储一个char。

cin >> nEKey 只读取abca 后面的cin >> nDKey 读取b 是输入中的下一个字符。

关于c++ - 为什么第二个 'cin >>' 不会被处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22665475/

相关文章:

c++ - SWIG:Lua - 将 C++ 实例作为 lua 函数参数传递

c++ - 调试语句放置修复了不一致的输出

java - 将电子邮件从本地文件系统恢复到 ews api 中的 Exchange 帐户

javascript - YouTube 视频持续时间 API v3

encryption - BouncycaSTLe 加密私钥 PEM 输出 : RSA PRIVATE KEY vs PRIVATE KEY

c++ - C++ 中迭代器的键/值功能

javascript - 使用带有用户输入的 vanilla js 从 (poke) API 中对 API 数据进行排序

c# - 椭圆曲线 Diffie Hellman 公钥大小

java - c# RSA 使用私钥加密

c++ - Eigen C++ 断言失败