2014-03-26 40 views
0

我是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,我是一个新手,只是不知道它的手段,任何人都可以帮助解决这个问题?

非常感谢!

回答

1

nEKeynDKey都是char类型,这意味着它们只能存储一个字符。

cin >> nEKey阅读只是abca和后期cin >> nDKey阅读b这是在输入下一个字符。

1
cin >> nEKey; // nEKey = 'a' 

将单字符读入nEKey。剩余的输入留在流中。你读下一个字符的下一次读:

//... 
cin >> nDKey; // nDKey = 'b' 

你应该读一个字符后忽略输入的其余部分。考虑使用std::string来读取字符串中的所有输入。

警告

warning '=':conversion from 'std::streamsize' to 'int',possible loss of data 

由可能的数据丢失包装较大std::streamsizeint时引起的。使用std::streamsize

std::streamsize nCount = cin.gcount(); 
1

cin >> nEKey;读取字符 'a',而不是字符串 “abc”。然后,cin >> nDKey;读取下一个字符(即'b')。

0

对于来自编译器的警告,尝试将cin.gcount()转换为int类型,如下所示。

nCount = (int)cin.gcount(); 

您应该确定字符串的大小可以包含在一个带符号的int中。

+0

他应该使用std :: streamsize nCount = cin.gcount(); – 4pie0

+0

你是对的。这样更安全。 –

相关问题