C++ cin.getline() 导致程序崩溃

标签 c++ cin

我正在制作一个简单的加密/解密程序...我是初学者。

#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <string>

using namespace std;

char s[1025];
char o[1025];
char key[1025];

char tochar(int a)
{
    if(a<26) return 'a'+a;
    if(a>25 and a<52) return 'A'+a-26;
    if(a>51) return '0'+a-52;
}
int toint(char t)
{
    if(t>='a' and t<='z') return 0-'a'+t;
    if(t>='A' and t<='Z') return 26+t-'A';
    if(t>='0' and t<='9') return 52+t-'0';
}

int main()
{
    int i,j,keylenght;
    //for(j=0;j<62;j++)cout<<j<<" "<<tochar(j)<<" "<<toint(tochar(j))<<endl;
    cout<<"Enter String:\n";
    cin.getline(s,1024);
    cout<<"Function [encrypt/decrypt]: ";
    char f;
    cin>>f;
    if(f=='e')
    {
        cout<<"Generate key? [y/n]: ";
        cin>>f;
        if(f=='y')
        {
            cout<<"Enter key length [up to 1024]: ";
            cin>>keylenght;
            srand(time(0));
            for(i=0;i<keylenght;i++)
            {
                key[i]=tochar(rand()%62);
            }
        }
        else
        {
            cout<<"Enter key: \n";
            cin.getline(key,1024);
            for(keylenght=0;key[keylenght]!='\0';keylenght++);
        }

        for(i=0;s[i]!='\0';i++)
        {
            if(key[keylenght%i]!=' ')
            {
                if(s[i]!=' ')o[i]=tochar((toint(s[i])+toint(key[i%keylenght]))%62);
                else o[i]=' ';
            }
            else
            {
                o[i]=s[i];
            }
        }
        cout<<endl<<"Encrypted string: "<<o<<endl<<"Generated key: "<<key;
    }
    else
    {
        cout<<"Enter key: ";
        cin>>key;
        for(keylenght=0;key[keylenght]!='\0';keylenght++);
        for(i=0;s[i]!='\0';i++)
        {
           if(s[i]!=' ')
           {
               if(key) o[i]=tochar((62+toint(s[i])-toint(key[i%keylenght]))%62);
           }
           else o[i]=' ';
        }
        cout<<endl<<"Decrypted string:\n"<<o;
    }
    return 0;
}

我第一次使用 getline() 时它工作得非常完美。但是,当我尝试使用它写入 key[] 字符串时,它会使程序崩溃。

谁能告诉我这是怎么回事?

最佳答案

问题是您正在混合输入类型。当你打电话时

cin>>f;

这会在输入缓冲区中留下一个换行符。然后在调用 getline() 键时仅获取换行符。您需要做的是在调用 getline 之前清除输入缓冲区。我喜欢使用:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

关于C++ cin.getline() 导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27491009/

相关文章:

c++ - 如何使用 select 正确检测我是在 Windows 还是 Linux 中构建 C++ 代码?

c++ - 如何更改 QStringListModel 项目的颜色?

c++ - 如何将 vector 字符串的值更改为不同的字符串值?

c++ - 如何将 ccsprite 转换为 ccimage cocos2dx

c++ - 异常处理中的冗余代码

c++ - 在没有临时变量的情况下直接将cin捕获到函数作为参数

c++ - cin.getline() 跳过

c++ - cin.ignore()为什么忽略getline输入的第一个字符?

让 cin 读取返回字符的 C++

c++ - cin 和 getline 跳过输入