The use of cin.get() to read a character(s) - c++

Can someone explain to me how cin.get() works below. My thinking is that cin.get() takes in a character from the keyboard (when you type it), assigns it to character1, then compares it to EOF, if this comparison is not equal, it prints it, then goes back to the while loop and does thesame until the EOF character is entered. What I expected to see is characters printed each time I enter them until EOF is entered but I am suprised to see that the program takes in characters until I enter EOF then it prints them all.
int character1;
cout << "Before input, cin.eof() is " << cin.eof()<< endl
<< "Enter a sentence followed by end-of-file:" << endl;
while ((character1 = cin.get()) != EOF)
cout.put(character1);
cout << "\nEOF in this system is: " << character << endl;

EOF/cin.eof() are not the same as the ASCII/tty EOF character(s). In both cases, the value is meaningful only in context, and may not actually exist otherwise.
On Windows EOF is signaled with Ctrl+Z.
On *nixen, it is signaled with Ctrl+D.
You cannot print it to the terminal either way. Tell the user to press the correct keys. And remember, the value of EOF has absolutely no relation to anything in the input stream (except being unrepresentable as a valid character value).
You see no output until you signal EOF because terminal input is, by default, line-buffered. Try pressing Enter during your input sequence to see the effect. If you wish to play with unbuffered input then that is a (lenghty) answer to another question.

Related

Pause Function it is Looping Forever

I am trying to implement a pause function in C++, but it is looping forever.
I am using macOS but I am trying to create a pause function that will work in any system... I believe my cin >> is not capturing '\n' or '\r' from the keyboard and it is looping forever.
void Transferencia::pause() {
char enter = 0;
while(enter != '\n' && enter != '\r') {
cout << "(Press Enter to Continue...) ";
cin >> enter;
}
cin.clear();
}
I want to pause my program until user press the key "enter".
But even when I press "enter/return" it keeps looping...
At very first: enter != '\n' || enter != '\r' is a tautology: Even if enter does equal one of the characters it cannot be equal to the other one. So one of the tests must be true... You actually want to stay in the loop when enter is unequal to both values.
std::cin >> ... won't read data before you press enter, but it will discard the newlines (actually, all whitespace). So it would suffice just to read one single character right without loop (the loop again would get an endless one); solely: If the user doesn't enter anything at all before pressing 'enter' key, there's no character to read from std::cin and we'd still be waiting.
What you can do is reading entire lines:
std::string s;
std::getline(std::cin, s);
That will accept empty lines as well, so does exactly what you want (note: no loop around!).
Edit (stolen from the comments; thanks, Thomas Matthews): An even more elegant way is
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
as it won't create any additional resources that would be discarded afterwards anyway (the std::string object!).
Edit 2:
Depending on type of last input operation, there might still be a newline (or even further data) buffered, e. g. after int n; std::cin >> n;. In this case, you need to skip the input yet buffered. So you would need ignore twice.
However, if the last input operation consumed the newline already (e. g. std::getline – or if there wasn't any preceding input operation at all), then this would lead to user having to press enter twice. So you need to detect what's has been going on before.
std::cin.rdbuf().in_avail() allows you to detect how many characters are yet buffered. So you can have:
if(std::cin.rdbuf().in_avail())
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "press enter" << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
On some systems (including mine), though, in_avail can return 0 even though a newline is yet buffered! std::cin.sync_with_stdio(false); can fix the issue; you should execute it before very first input operation. Hopefully, you don't use C++ (streams) and C (scanf, printf, etc) IO intermixed then...
The easiest way to do this is with getline().
cin >> ignores whitespace, newline characters included. getline() will read an entire line, newline character included. However, it does not copy the newline character to the output string. If the user simply hit the enter key and nothing else, you'd end up with an empty string.
So, to get your desired behavior, you would construct your loop like this:
string line;
while(true)
{
cout << "(Press Enter to Continue...) " << endl;
getline(cin, line);
if(line == "")
break;
}
#Aconcagua has answered your question but this is what I want to add in.
Normally, for handling some specific kind of event in computer, we usually follow event-driven paradigm or event-callback.
The idea is there is an event loop that waits for a new event coming into the system. This case, keyboard is an event, the event loop then calls event-callback. What event-callback does is it compares the value of input with some conditions then do some other tasks (it might change some state of the program or notify users).
The idea is keep CPU busy by either 2 ways.
event-driven : do other tasks while waiting for a new event
multithreading: multiple threads in the system. This approach has the disadvantage is at data-race
Have fun

How to move cursor to end of text output after cin.clear() and cin.ignore()?

After clearing invalid input with std::cin.clear() and std::cin.ignore(), the cursor moves to the beginning of the next line printed by std::cout. I experimented with including an extra std::endl in various positions, to no avail.
Is there any way to force the cursor to the end of the line?
Prompt
do {
std::cout << "Enter a number: ";
if(!(std::cin >> number)) {
std::cout << "Not a number. Try again..."<< std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
}
} while (number != -1);
Output
Enter a number: |
Invalid input. Try again...
|Enter a number:
'|' represents the cursor position
std::cout isn't always what you think it is. It's not "the output to the terminal" - it could be output to a file, or even printer. Moving the cursor around on a printer wouldn't do what you might want it to do.
As such, you could TRY printing backspace characters (\b) and see what happens, but better yet would be to obtain a terminal library - like ncurses; which will give you far better control of the cursor.

Why is cin.failbit always set even when input is valid?

I was trying to write a program that asks to input a char array using cin.getline() and if given input is bigger than array length array gets extended.
I used cin.failbit to see if user's input was too long. But nothing went right. So after debugging I figured out that the problem lies in failbit.
So I wrote a simple program to see what was wrong about it and it turned out that somehow cin.failbit always returns true when in if-statement even when input seems valid.
int main () {
char name[256];
std::cout << "Enter your name: ";
std::cin.getline (name,256, '\n');
std::cout << "characters read: " << std::cin.gcount() << std::endl;
if (std::cin.failbit){
std::cin.clear();
std::cout << "failed\n";
}
}
For example, when input is "qwer" program outputs that 5 characters have been read (cin.gcount), so it should be fine but it also outputs "fail" meaning that failbit flag is set. But I believe it shouldn't be in this case.
program output here
So can anyone explain why failbit appears to be set permanently?
Any help will be highly appreciated
std::cin.failbit is a constant that indicates which of the error bits represents stream failure. It is not an indication of the stream's current state. To check if that bit is set, use the member function std::cin.fail() instead.
However, if the stream failed to read due to reaching the end of the stream fail() will return false leading you to believe that it succeeded. Prefer std::cin.good() to check if the last operation succeeded.

Holding the console-screen when end-of-file is involved

Here's the scaled down version of the program which accepts an unknown no. of Integer inputs. I used cin.get() before but to no avail, finally used this but unfortunately it too didn't worked. I am using Notepad++ spawning command prompt to run my programs. Is this something to do with Notepad++ OR the CTRL-Z (end-of-file) character?
EDIT : Works fine using cmd.exe
vector<int> vint;
int val = 0;
cout << "Enter integers..... Press CTRL and \'Z\' when done entering!"
<< "\n GO... : ";
while(cin >> val)
vint.push_back(val);
if (vint.size() > 1)
{
...
}
else
{
...
}
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n' );
std::cin.get();
When you enter Ctrl+Z in a console programme you tell that it's the end of the file. Any subsequent reading from cin is then doomed to fail.
It works from the command line, because the command processor doesn't close the window when the programme is over.
Possible solutions:
The portable approach would be to interupt the loop cleanly by checking for a special value (for example 0).
If this is not possible, another approach would be to gain more control on the user input and read lines into a string. You could then end the loop when an empty line is entered. This is I think for the user the most intuitive approach. All you have to do is to parse non empty strings with stringstreams (and eventually complain if non numeric values were entered).
An less perfect approach could be to instruct the user to enter some non numeric value to end the loop. You then have to clear the failure that invalid input would generate:
while (std::cin >> val ) {
...
}
if (std::cin.eof()) // display the special case
std::cout <<"End of file encountered !" << std::endl;
std::cout << "Press a key...";
std::cin.clear(); // clear the error state of cin
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
Surprisingly, this works compiled with MSVC2015 on windows when entering Ctr+Z: once the end of file state cleared the console is magically restored and you can continue to read. However you can't assume this to work with console front-ends like Notepad++, nor with other implementations of the standard library, nor on other OS.

How while(!(cin >> x)) works to re-prompt for input

while(!(cin >> ar[i]))
{
cin.clear(); // clears bad input
while(cin.get() != '\n')
continue;
cout << "Invalid input, please enter valid scores";
}
The above code is from a much larger file. I copied this bit of a code from one of my textbooks and I don't really feel comfortable using it as I do not understand how this works.
I am using it as a measure to handle input errors.
So ar is an empty array of integers, if I decide to enter 'k', then
!(cin >> ar[i])
is true.
From here I clear the input buffer (I think that is correct, I'd like someone to confirm or dispute this please). The terminal then prints "Invalid input..."
Now if I just press Enter nothing happens, but isn't Enter the newline char? So shouldn't the code read
while(cin.get() == '\n'
?
while(!(cin >> ar[i]))
This tries to parse a value from cin and store it in ar[i]. By default, >> skips whitespace first, then sees if the characters in cin describe a legal value for whatever the type of ar[i] is. If a legal value is found, then cin stream state remains good, and its operator bool() const will kick in given the boolean not/! operation, such that the while loop will break.
If parsing fails though, the stream state will be set to one or more of:
bad (if there's some unrecoverable stream error, like stdin supplied over a network connection that gets disconnected),
fail (if the characters just didn't form a legal value for the type), or
eof (end of file, for a "proper" shutdown/close of the input, as supplied by ^D in UNIX/Linux, ^Z in Windows, and the end of input when a program's invoked as in echo input | program).
All the above modalities are described under "State Functions" here.
If the loop is entered due to any of the error conditions above...
{
cin.clear(); // clears bad input
...this does NOT clear any input data from the stream, but does clear the bad, eof and fail state flags, after which further input attempts can be made, though a stream that was in bad or eof state is likely to immediately reenter that state when further input is attempted (but not always - some OS may allow successful input after an eof conditions for std::cin if the user types/generates an EOF code then types actual text again...
while(cin.get() != '\n')
continue;
This tries to read characters from the terminal until a newline \n is encountered. The idea's clearly to clear out the rest of the presumed unparse-able input that might have led to a fail condition earlier. Sadly, if the problem was, or becomes, a bad or eof condition then this loop will hang the program, spinning burning CPU to no avail.
cout << "Invalid input, please enter valid scores";
}
If the problem was simply a mistyped value and no bad or eof condition, then the cout will prompt for further input.
Now if I just press enter nothing happens, but isnt enter the newline char?
Whenever the outer loop is executing cin >> ar[i] it will skip whitespace, including any extra newlines you type, until it sees some input (which may need to be a full newline-terminated line to get flushed by the terminal or program feeding it to the program), or a bad or eof condition. The inner while-loop is not there to get rid of empty lines - it's trying to discard the line with presumed non-numeric text in it.
Corrected code:
while (!(std::cin >> ar[i]))
{
if (std::cin.bad() || std::cin.eof())
{
std::cerr << "Fatal error on cin while reading numbers\n";
exit(EXIT_FAILURE);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, please enter valid scores\n: ";
}
The goal of this entire code is to keep printing errors and requesting input until the user enters a valid number before continue further into the program.
The loop that the entire code is enclosed in...
while(!(cin >> ar[i]))
says to loop if the input in the cin stream is invalid. Since ar is an array of integers, the input would be invalid if it is not a number.
cin.clear(); // clears bad input
When the cin stream encounters invalid input, the program begins executing the loop and continues to this line of code. Since the stream encountered invalid input, it has a flag that says there is an error. This requires that you, as the comment puts it, "clear bad input." Basically what this does is get rid of this flag. If this is not done, the flag will remain in the stream and the program will encounter another error next time the cin stream is used, regardless of whether or not the user input is valid.
while(cin.get() != '\n')
continue;
When the program took the input from the user, it took the string, char, whatever was the invalid input, but left the '\n' in the cin stream. To prevent errors the next time the cin stream is used, the program must get rid of that '\n', along with anything else that was lefty behind. cin.get() reads only one char from the cin input stream and returns it. Since the return value of this function is not being assigned to anything, all this does is discard the char that was read. In the case that more than the '\n' was left behind in the stream, this loop checks the value of the read char before disposing of it. This way, the loop keeps executing while the char that is read is NOT '\n'. Or in other words, it loops until the char that is read IS '\n'. The only thing that continue does, is tell the program to skip the rest of the current iteration of the loop and start the next iteration. In this situation, this is equivalent to giving the loop an empty body. You could very well replace continue; with {} and the program would do the exact same thing.
cout << "Invalid input, please enter valid scores";
The program has cleared the flag in cin and has also cleared any data from cin that may have been left behind. Now that all the errors from the invalid input have been handled, there is only one more thing to do. It's time to notify he user that the input was invalid and request new input. If the user enters more invalid input, the loop repeats. If the user enters valid input, the program continues on to the next line of code.