我的程序进入cin.getline()函数时突然退出

问题描述 投票:-2回答:1

我使用getline()函数编写了一个程序。

code

我认为问题出在这部分:

    int encrypt(){
    int opt,limit;
    char inp[100],enc[100];
     cout<<"Choose the encryption type\n"
        <<"[1]Simple\n"
        <<"[2]complex\n"
        <<">>>";
    cin>>opt;
    if(opt==1){
    cout<<"Enter string to be encrypted :";
    cin.getline(inp,100);
    limit=strlen(inp);
    for(int i=0;i<limit;i++)
        {
        switch(inp[i])
                {
                case 'a' :  enc[i]='q';
                            cout<<enc[i];
                            break;

                ..........

它打印enter string to be encrypted,然后突然退出:p

提前感谢

c++ function g++ getline cstdio
1个回答
0
投票
cin >> opt后的

cin.ignore(),应完成此工作(快速修复)。 @Algirdas引用了一个可为您提供更多详细信息的链接,这是因为由于opt的输入而使您进入了换行符。

int encrypt(){
int opt,limit;
char inp[100],enc[100];
 cout<<"Choose the encryption type\n"
    <<"[1]Simple\n"
    <<"[2]complex\n"
    <<">>>";
cin>>opt;
if(opt==1){
cout<<"Enter string to be encryped :";
cin.ingore() #this can help in clearing the '/n' in stream
cin.getline(inp,100);
limit=strlen(inp);
for(int i=0;i<limit;i++)
    {
    switch(inp[i])
            {
            case 'a' :  enc[i]='q';
                        cout<<enc[i];
                        break;

            ..........

尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.