Hello dallin56,
There is nothing wrong with your code, but with your understanding of formatted and unformatted input, i.e., (std::getline(), unformatted input, and cin >> tf, formatted input.
Formatted input will extract from the input buffer up to a white space or newline, (\n), whichever comes first.But it leaves the (\n) in the input buffer.
Unformatted input, the "std::getline", will extract everything from the input buffer including the (\n) and then disgard the (\n) leaving the input buffer empty.
As
jonnin mentioned there are several ways to clear the input buffer:
1 2 3
|
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
std::cin.ignore(1000, '\n').
Or use the defaults of the function std::cin.ignore(); // <--- 1 character or the "\n" whichever comes first.
|
For your code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <string>
//using namespace std; // <--- Best not to use.
int main()
{
std::string message;
char tF = 'n';
while (tF == 'n')
{
std::cout << "\n Please enter message to encode:\n> ";
std::getline(cin, message);
//std::cout << "\n Is this correct? y/n: " << endl << message << endl;
std::cout << " Is this correct? y/n: ";
std::cin >> tF;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
}
return 0;
}
|
This is untested, but should work.
First your program defines a "std::string" then you use "std::getline" and finally a "cout" statement the prints the "std::string" message. All of these need the header file "<string>" to work properly otherwise your compiler should be complaining.
Other than the addition of line 2 line 20 is the most portable way of writing this that can be used by any compiler and header files.
In line 13 I changed the prompt a little.
For line 17 There is no real point in printing the message that was just entered. You can still see what was entered you just need to know if it is correct or not.
Some of the changes are a suggestion, so see what you think.
Andy