C++ 没有脱离循环
我用这个程序来实现单字母密码。我遇到的问题是,当我输入纯文本时,当满足条件(按enter键)时,它不会退出循环。这是我的代码C++ 没有脱离循环,c++,loops,C++,Loops,我用这个程序来实现单字母密码。我遇到的问题是,当我输入纯文本时,当满足条件(按enter键)时,它不会退出循环。这是我的代码 int main() { system("cls"); cout << "Enter the plain text you want to encrypt"; k = 0; while(1) { ch = getche(); if(ch == '\n') {
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;
}
intmain()
{
系统(“cls”);
cout这里的问题可能是这样一个事实:getche()
(与getchar()
)不同,当有多个输入且您在windows上时(否则您将不使用cls
),然后EOL用\r\n
编码
发生的情况是,getche()
返回\r
,因此中断从未实际执行。即使getche是非标准函数,也应将其更改为getchar()
你可以尝试寻找<代码> \r>代码>,而不是在你的情况下,<代码> \n < /> >但是我想<>代码> \n>代码>如果你需要在以后获取任何额外的输入(不确定),就会造成问题。
依赖于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;
}
#包括
#包括
使用名称空间std;//憎恨者会憎恨
char transform(char c)//替换为您拥有的任何内容
{
如果(c>=‘a’& & c=‘a’& & c我会做一些类似于使用标准C++ I/O < /P>的休耕。
#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;
}
#包括
#包括
使用名称空间std;
//你需要填写这张表。
字符arr[]={'Z','Y','X'};
字符键[]={'A','B','C'};
int main(int argc,_TCHAR*argv[]
{
弦输入;
char sOutput[128];
int k;
库特>辛普特;
对于(k=0;k
换行符是否被命中?如果没有,getche是否捕获换行符?@devshorts这就是问题所在,它没有获取换行符。您是否有可能在Widnows机器上遇到此问题?请尝试“\r”而不是“\n”您应该做的是cout
由getche
返回的字符代码。当您点击enter键时,您将看到该键生成的第一个代码;当您收到该代码时,将其中断,一切可能都会正常。但是,它不应该在\r
之后得到\n
吗?它应该使用getchar
,它实际上不使用getche
来完成。啊,你刚刚打败了我。getche
显然是c的一部分onio.h
,这是一些老式的MSDOS代码,因此不应该再使用了。