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
Use :
cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
to eat newlines from previous input std::cin >> op;
header - <limits>
Other way would be :
while (std::getline(std::cin, str)) //don't use string
if (str != "")
{
//Something good received
break;
}
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.
This is because you still have the newline character in the buffer which makes getline()
stop reading as soon as it encounters it.
Use cin.ignore()
to ignore the newline character from the buffer. This will do in your case.
In general, if you want to remove characters from your buffer untill a specific character, use:
cin.ignore ( std::numeric_limits<std::streamsize>::max(), ch )
As other stated already, the formatted input (using in >> value
) start skipping space abd stop when they are done. Typically this results in leaving some whitespace around. When switching between formatted and unformatted input you typically want to get rid of leading space. Doing so can easily be done using the std::ws
manipulator:
if (std::getline(std::cin >> std::ws, line)) {
...
}