2012-09-19 99 views
0

我正在使用这个程序来实现单声道字母密码。我得到的问题是,当我输入纯文本时,它不会退出循环,当条件满足时,按下回车键。这里是我的代码。没有走出循环

int main() 
{ 
    system("cls"); 
    cout << "Enter the plain text you want to encrypt"; 
    k = 0; 
    while(1) 
    { 
     ch = getche(); 
     if(ch == '\n') 
     { 

      break; // here is the problem program not getting out of the loop 
     } 
     for(i = 0; i < 26; i++) 
     { 
      if(arr[i] == ch) 
      { 
       ch = key[i]; 
      } 
     } 
     string[k] = ch; 
     k++; 
    } 
    for(i = 0;i < k; i++) 
    { 
     cout << string[i]; 
    } 
    getch(); 
    return 0; 
} 
+0

休息是否受到打击?如果不是,getche是否捕获换行符? – devshorts

+0

@devshorts这就是它没有获得换行符的问题。 – james

+0

有没有机会在Widnows机器上发生这个问题? – monksy

回答

3

这里的问题可能是,getche()(不像getchar())刚刚返回时,有一个以上inputed和你使用的是Windows(othewise你不会使用cls)的第一个字符的事实则是EOL编码为\r\n

会发生什么事是getche()返回\r所以你的休息是从来没有实际执行。即使因为getche是一个非标准函数,您应该将其更改为getchar()

你甚至可以尝试寻找\r,而不是在您的情况\n但是我想\n将继续留在缓冲区造成问题,如果以后需要获取任何额外的输入(不知道它)。

+0

不应该在'\ r'之后得到'\ n'吗? –

+0

它应该用'getchar',它实际上并不用'getche'来做。 – Jack

+0

啊,你刚刚打败了我。 'getche'显然是'conio.h'的一部分,这是一些老派的MSDOS代码,因此不应该再使用。 – Rook

2

依靠C++中的旧C库很可惜。考虑这个替代方案:

#include <iostream> 
#include <string> 

using namespace std; // haters gonna hate 

char transform(char c) // replace with whatever you have 
{ 
    if (c >= 'a' && c <= 'z') return ((c - 'a') + 13) % 26 + 'a'; 
    else if (c >= 'A' && c <= 'Z') return ((c - 'A') + 13) % 26 + 'A'; 
    else return c; 
} 

int main() 
{ 
    // system("cls"); // ideone doesn't like cls because it isnt windows 
    string outstring = ""; 
    char ch; 
    cout << "Enter the plain text you want to encrypt: "; 
    while(1) 
    { 
     cin >> noskipws >> ch; 
     if(ch == '\n' || !cin) break; 
     cout << (int) ch << " "; 
     outstring.append(1, transform(ch)); 
    } 
    cout << outstring << endl; 
    cin >> ch; 
    return 0; 
} 
2

我会做类似使用标准C++ I/O的休闲方式。

#include <iostream> 
#include <string> 

using namespace std; 

// you will need to fill out this table. 
char arr[] = {'Z', 'Y', 'X'}; 
char key[] = {'A', 'B', 'C'}; 

int main(int argc, _TCHAR* argv[]) 
{ 
    string sInput; 
    char sOutput[128]; 
    int k; 

    cout << "\n\nEnter the plain text you want to encrypt\n"; 
    cin >> sInput; 

    for (k = 0; k < sInput.length(); k++) { 
     char ch = sInput[k]; 

     for(int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) 
     { 
      if(arr[i] == ch) 
      { 
       ch = key[i]; 
       break; 
      } 
     } 
     sOutput[k] = ch; 
    } 
    sOutput[k] = 0; 
    cout << sOutput; 

    cout << "\n\nPause. Enter junk and press Enter to complete.\n"; 
    cin >> sOutput[0]; 

    return 0; 
}