C++ getline方法不起作用

Juj*_*nol 1 c++ encryption cin

对不起,我对C++很新,但不是一般的编程.所以我试着做一个简单的加密/解密.但是,当我将修改添加到我之前的代码中时(因此没有两个加密和解密程序),我发现代码'getline()'方法不再有效.相反,它只是在代码运行时忽略它.这是代码:

int main(){
    std::string string;
    int op = 1; //Either Positive or Negative

    srand(256);
    std::cout << "Enter the operation: " << std::endl;
    std::cin >> op;
    std::cout << "Enter the string: " << std::endl;
    std::getline(std::cin, string); //This is the like that's ignored

    for(int i=0; i < string.length(); i++){
        string[i] += rand()*op; //If Positive will encrypt if negative then decrypt
    }
    std::cout << string << std::endl;

    std::getchar(); //A Pause 
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*pel 7

那是因为在你的代码中std::cin >> op;留下了一个悬念\n,这是第一件事getline.由于getline一旦找到换行符就停止读取,该函数立即返回,不再读取任何内容.您需要忽略此字符,例如,使用cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');(std::numeric_limits在标头中定义<limits>),如cppreference中所述.