C++ getline(cin, variable) is misbehaving. No solutions on the site have helped - c++

My code is rather simple. I have a method called promptUserInput that is defined in UtilityFunctions.h; it is implemented in UtilityFunctions.cpp.
My main method includes UtilityFunctions.h. I've correctly written my makefile, and it compiles without issue.
My main method's first line reads:
string input = promptUserInput();
And here's the actual implementation of the promptUserInput function:
/* Prompts user to enter expression */
string promptUserInput()
{
string userInput;
cout << "> ";
getline(cin, userInput);
return userInput;
}
But when the program runs, it doesn't display the > symbol. Instead, there's an empty line waiting for user input. I enter some arbitrary character, hit Enter, and the > symbol appears afterwards. None of this makes sense to me. What's going on?

std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.
You can also use std::cout << std::endl, which writes a line break and then flushes, but the line break might not satisfy your intention.

Related

Proper use of EOF (can it be used multiple times in a program?)

In my intro to programming course (c++), the instructor told us to:
"Write a program that inputs an unspecified number of integer ("int")
values and then outputs the minimum value and the maximum value that
were entered. At least one value will always be input. (read all input
until EOF). For extra credit make your program also work when the user
doesn't enter any ints at all (just the EOF.)"
I wanted to get fancy, so, in my solution, when just EOF is entered, the program responds with "Oops! You didn't enter anything. Please try again, this time entering at least one integer: " and prompts for input again.
My instructor is saying that this answer is wrong because
After the EOF, there should be no more input to a program (neither
expected by the user nor the program) — using the EOF to switch from
“one mode” of input to another mode of input isn’t supporting the
standards.
Every definition of EOF I've found on the internet doesn't seem to support my professor's definition. EOF, from what I can tell, is simply defined as the end of the current file. It seems perfectly valid to accept input from a user until EOF, do something with that input, and then ask for additional input until EOF again.
Because this is an online course, I was able to review everything we learned relating to EOF and we were only told that EOF meant "End of File" and could be 'used to signal an end to user input' (important, because, even if my professor was wrong, one could argue that I should have adopted his standards if he had specifically told us to. But he didn't tell us to).
What is the proper way to use EOF with user input? Is my professor's statement that "After the EOF, there should be no more input to a program" the standard
and expected way to use EOF? If a program accepts a variable amount of input, does something with it, and then accepts more variable input, is it not acceptable to use EOF with those inputs (aka don't use while(cin >> user_input) in that scenerio)? If so, is there a standard for what should be used to signal end of input in a scenario where you're accepting variable input multiple times?
My exact solution to the assignment is below. My solution to the main assignment "Write a program that inputs an unspecified number of integer ("int") values and then outputs the minimum value and the maximum value that were entered" was considered correct, by the second part of the assignment "make your program also work when the user doesn't enter any ints at all (just the EOF.)" was deemed incorrect ("make the program also work" is the only prompt we were given).
Thanks so much for any feedback!! Obviously, I'm skeptical of my professors feedback / decision, but, in general, I'm just trying to get a sense of C++ community standards.
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
string user_input;
int int_input, min_user_input, max_user_input;
bool do_it = true;
cout << "Hi John," << endl;
cout << "Please enter a few integers (signal EOF when finished): ";
while(do_it) {
cin.clear();
cin >> user_input;
if (user_input.empty()) {
cout << endl;
cout << "Oops! You didn't enter anything. Please try again, this time entering at least one integer: ";
}
else {
try {
int_input = atoi( user_input.c_str() );
min_user_input = int_input;
max_user_input = int_input;
while(cin >> int_input) {
if (min_user_input > int_input) {
min_user_input = int_input;
}
if (max_user_input < int_input) {
max_user_input = int_input;
}
}
cout << endl;
cout << "The max user input was: " << max_user_input << endl;
cout << "The min user input was: " << min_user_input << endl;
do_it = false;
}
catch (std::invalid_argument) {
cout << endl;
cout << "Oops! You didn't enter an integer. Please try again, this time only entering integers: ";
do_it = true;
}
}
}
return 0;
}
Note: additional feedback I got on this submission was: to not use c libraries (apparently stdlib.h is one) and that, on some computers (though, apparently, not mine), #include <stdexcept> will be needed to compile.
Answer
Short answer: my instructor is correct. When used with cin, no additional user input should follow an EOF signal. Apparently, in some cases the program won't let you enter more information, but, as #hvd points out
Although your system may let you continue reading from the same file
in the specific case that it is coming from a TTY, due to EOF being
faked there, you shouldn't generally rely on that.
Aka, because I'm using a terminal to enter user input, the program happens to work. In general, it won't work though.
As #RSahu answers, EOF just shouldn't be used to signal the end of variable length cin multiple times in a program. Importantly
There is no standard means, or commonly practiced coding standard, of
indicating when user input has ended for the time being. You'll have
to come up with your own mechanism. For example, if the user enters
"end", you can use it to deduce that the user has ended input for the
time being. However, you have to indicate to the user that that's what
they need to enter. Of course, you have to write code to deal with
such input.
Because this assignment required the use of EOF, what I was attempting to accomplish was, unintentionally, prohibited (aka receive input, check it, possibly receive more input).
Proper use of EOF (can it be used multiple times in a program?)
There is no single EOF. There is EOF associated with every input stream.
If you are reading from a file, you can reset the state of the std::ifstream when it reaches EOF to allow you to read the contents of the file again.
However, if you are reading data from std::cin, once EOF is reached, you can't read from std::cin any more.
In the context of your program, your professor is right. They are most likely talking about reading from std::cin.
EOF, from what I can tell, is simply defined as the end of the current file.
It is. Note that in particular, what it doesn't mean is the automatic start of a new file.
Although your system may let you continue reading from the same file in the specific case that it is coming from a TTY, due to EOF being faked there, you shouldn't generally rely on that. Try program </dev/null and see happens when you try to automate your program.

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.

Stop new line for C++ cin

In C++, iostream automatically puts in a new line after cin. Is there a way to get rid of this?
I want use iomanip to format information into a table, like so:
cin cout
0.078125 3DA00000
-8.75 C10C0000
23.5 41BC0000
(random numbers)
example code:
#include <iostream>
using namespace std;
int main()
{
int num;
cin >> num; //now a new line.
cout << num << endl;
return 0;
}
You presumably pressed the return key to send your input from the command line to your program's standard input. That's where the newline is coming from. You can't read your number from cin before this newline appears in the console, because the newline is what causes the console to hand your input over to the program in the first place. You could, as a user, configure your console (or whatever is running your program) to act differently, but there's no way for the program itself to force such behavior.
If you really want to have your input and your output on the same line, you need to find a way to "write to the previous line". How that works depends on your console (see also How to rollback lines from cout?). There is no standard way to do this because cin and cout are in no way obligated to be attached to a console or anything resembling one, so it is not clear that "writing to the previous line" even means anything.
'endl' makes a new line just don't use it.
cout << num;

Keep looping until user enters a blank line?

So I've run into the following problem. My goal is to create a loop that keeps taking user input over and over until the user doesn't enter anything into 'cin >>', leaves the line blank, and simply presses the ENTER key to move on, at which point the program is supposed to break out of the loop and continue on with the rest of program execution. Something like this:
do {
cout << "\nEnter a name: ";
cin >> input1;
if (input1.empty())
{
break;
}
else
{
user_name = input1;
}
} while (!input1.empty());
As you can see, I've already tried using the empty() function, but that didn't work, the program simply stays in the loop and doesn't break out, no matter how many times I press enter. It just keeps prompting me to enter a name. I've also tried using something like
if (input1 == "")
but that doesnt work either. Can anyone help? How do I break out of this loop?
UPDATE: OK guys, I've tried your recommendations, and it worked! Thank you so much! Unfortunately, although the getline function works, it has also created a new problem for me. Basically, in the first initial loop, the program prompts for a name, I type in a name, and the name is stored in user_name. However, in the SECOND loop, the program doesn't even give me the chance to enter any input, it simply prints "Enter a name: ", and then instantly exits out of the loop, and continues on with the rest of program execution. Why is this happening?
Use this getline(std::cin, input1):
while (getline(std::cin, input1))
{
if (input1.empty())
break;
username =input1;
std::cout << input1 << std::endl << "Enter Input : ";
}
Use std::getline(cin, input1); instead to read a line from the console.
Using cin directly reads exactly one word from stdin. If the user does not input anything, no word has been given and cin does not return yet (your empty check is not even executed).
After you use std::getline you can leave your empty-check as-is:
std::getline(cin, input1);
if(input1.empty())
break;
BTW: In C++ you should also check if the underlying stream has run into an error. So check the return code of cin or getline. This can be done with the following code:
if(!std::getline(cin, input1))
// I/O error
In general, looping until an empty line is entered would be:
while ( std::getline( line ) && !line.empty() ) ...
If you need a prompt: the prompt is part of the input logic, and
should be implemented as such:
std::string
getlineWithPrompt( std::string const& prompt )
{
std::cout << prompt;
std::string results;
return std::getline( std::cin, results )
? results
: std::string();
}
You then do something like:
std::string line = getlineWithPrompt( "prompt for first line" );
while ( !line.empty() ) {
// ...
getlineWithPrompt( "prompt for further line" );
}
(This is actually somewhat simplified, as it treats hard errors
on input, end of file, and empty lines identical, which is
rarely the right thing in professional software. But for
learning purposes, it should be sufficient.)
Cin won't read the whitespace that you call an empty line. Getline may do this, but I am not entirely sure. You could define an end character that the user would type and check for that. Gets would also work, it will just set the starting character to 0x0. Be careful with gets(), it is prone to allow buffer overflows.
This works as well:
char line[128];
do
{
cout << "Enter something: ";
gets(line);
} while (strcmp(&line[0], "\0") != 0);
#JamesKanze
So something like this to exit the while loop?
string str = "foo";
while (str == "foo"){
getline(cin, str);
}
str = "foo";

C instruction is being reordered when cin cout and gets is used consecutively

Does anyone knows why C instruction is being reordered when cin cout and gets is used consecutively here?
I am using Dev-C++ 4.9.9.2.
#include<iostream>
using namespace std;
int main(){
char a[10],b;
for(;;){
cout<<"\ncin>>b:";
cin>>b;
cout<<"gets(a):";
gets(a);
cout<<"cout<<a<<b:"<<a<<" "<<b<<"\n\n";
}
}
I got an output like:
cin>>b:132
gets(a):cout<<a<<b:32 1
cin>>b:465
gets(a):cout<<a<<b:65 4
cin>>b:312242
gets(a):cout<<a<<b:12242 3
cin>>b:1
gets(a):cout<<a<<b: 1
cin>>b:
It seemed like some input for cin was passed in gets.. and it also appears that instructions were reordered like:
cin>>b;
gets(a);
cout<<"gets(a):";
instead of,
cin>>b;
cout<<"gets(a):";
gets(a);
cin>>b read just a character, leaving the rest of the input to be read by later input operation. So gets sill has something to read and don't block.
At the first cin >> b, there is no input available. You enter '132\n' (input from terminal is usually made line by line) in a buffer and just get the 1 out of it. gets reads the next characters 32 and the \n which terminates gets. It doesn't need to read something more from the terminal.
Nothing has been re-ordered.
your input from keyboard has been send only when you pressed enter. At that time, there have been enough data to execute the cin<<b, the following cout, then to complete the gets(a).
In others words, the execution of cin<<b is suspended to the reception of a char. But that char is not send to the program until you pressed 'Enter' (this is because of your terminal settings). When you press 'Enter', the first char is received by cin<<b and the remaining is buffered. cout executes, and when it is the turn of gets(a), the buffer delivers the remaining chars included the carriage return, so gets(a) completes as well, with the data you entered to complete the cin<<b instruction.
Try to simply press enter for the cin<<b to complete, then you'll see the cout, and then you will have the gets(a) waiting for your inputs.
While not really answering your question...
The idiomatic way in C++ would rather be to use getline. It's an accident of history that does not make it part of the iostream interface directly, but it really is the function to use for inputs.
Shameless plug from the website:
// getline with strings
#include <iostream>
#include <string>
int main () {
std::string str;
std::cout << "Please enter full name: ";
getline (std::cin,str);
std::cout << "Thank you, " << str << ".\n";
}
The main advantage of getline, in this version, is that it reads up until it encounters a line-ending character.
You can specify your own set of "line-ending" characters in the overload accepting a third parameter, to make it stop on commas or colons, for example.
The code isn't reordered, but std::cout is buffered so the string doesn't appear immediately on your display. Therefore gets(a) will be executed with the output still in the buffer.
You can add a <<flush after the output string to make cout flush it's buffer.
When you use std::cin, it knows how to tell std::cout to flush the buffer before the input starts, so you don't have to.