我是C++新手,去年我学习了Java,并且在本学期中我必须学习使用C++和MFC/API的密码编程,现在很多人都感到困惑,无论如何,请看代码:为什么第二个'cin >>'不会被处理?
#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 ++以及在视觉工作室编译它,它们产生相同的输出。
现在我的问题是:为什么第二个cin不会被处理?
而在Visual Studio中它给了我一个警告说:
...\enc.cpp(25): warning C4244: '=' : conversion from 'std::streamsize' to 'int', possible loss of data
OMD,我是一个新手,只是不知道它的手段,任何人都可以帮助解决这个问题?
非常感谢!
他应该使用std :: streamsize nCount = cin.gcount(); – 4pie0
你是对的。这样更安全。 –