Search code examples
c++encryptioncin

C++ getline method not working


I'm sorry but I'm quite new to C++ but not programming in general. So I tried to make a simple encryption/decryption. However when I added the modification to my previous code (so there isn't two programs for encrypting and decrypting) I found that the code 'getline()' method no longer works. Instead it's just ignoring it when the code is ran. Here's the code:

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;
}

Solution

  • That's because std::cin >> op; leaves a hanging \n in your code, and that's the first thing getline reads. Since getline stops reading as soon as it finds a newline character, the function returns immediately and doesn't read anything more. You need to ignore this character, for example, by using cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); (std::numeric_limits is defined in header <limits>), as stated on cppreference.