c++ stop asking for input on ctrl-d - c++

I am trying to read user input until ctrl-d is hit. If I am correct, ctrl+d emits an EOF signal so I have tried checking if cin.eof() is true with no success.
Here is my code:
string input;
cout << "Which word starting which year? ";
while (getline(cin, input) && !cin.eof()) {
cout << endl;
...
cout << "Which word starting which year? ";
}

So you want to read until EOF, this is easily achieved by simply using a while loop and getline:
std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
Here using getline(getline returns the input stream) you get the input, if you press Ctrl+D, you break out of the while loop.
It's inportant to note that EOF is triggered different on Windows and on Linux. You can simulate EOF with CTRL+D (for *nix) or CTRL+Z (for Windows) from command line.
Keep in mind that you might exit the loop in other conditions too - std::getline() could return a bad stream for some failures and you might want to consider handling those cases too.

Related

getline is not waiting for the input

I am trying to read the n-th line from the standard input in the following program. However, the console will print out "current line is" before I input any number...not sure what's wrong. Thanks for help.
int main()
{
string currentLine;
int n;
cin >> n;
cout << n << endl;
while (n > 0)
{
getline(cin, currentLine);
cout << "current line is" << currentLine << endl;
n--;
}
return 0;
}
The formatted input using operator>>() stops as soon as its format can't be satisfied by the next character. For integers it stops when there is no further digit, e.g., when the next character is a whitespace like the newline from entering the line.
std::getline() reads until it finds the first newline. There was one left right before when reading the integer. You probably want to extract this newline and potentially other whitespace. You could, e.g., use
if (std::getline(std::cin >> std::ws, currentLine)) {
// do something with the current line
}
else {
// deal with a failure to read another line
}
The manipulator std::ws skips leading whitespace. As indicated above, you should also verify that the input was actually successful before processing input.
In order to get n, you have to input a number and press the Enter button. As #Kuhl said, the operator>> stops as soon as its format can't be satisfied by the next character.
This means the first time getline(cin, currentline) runs will get '\n' !
Then the program will output "current line is\n" while the '\n' will not be shown on the console.
If you want to get n and 'currentline', you may choose the #Kuhl's answer or write the program like this:
getline(cin, currentline);
while(n>0) {
// anything you want
}
The getline(cin, currentline) will help you to skip the '\n' followed by the number 'n'.

getline() not waiting for input inside switch...case (C++)

I'm trying to get input from the user using getline().
The following code works fine. It waits for the user to type the file name and stores it in fileName.
#include <iostream>
#include <string>
using namespace std;
string inputFile();
int main()
{
string fileName;
cout << "Enter the name of the file including the path" << endl;
getline(cin, fileName);
return 0;
}
However, this code does not work fine.
#include <iostream>
#include <string>
using namespace std;
string inputFile();
int main()
{
int option;
cout << "Enter option number" << endl;
cin >> option;
switch (option)
{
case 1:
{
string fileName;
cout << "Enter the name of the file including the path" << endl;
getline(cin, fileName);
break;
}
case 2:
cout << "You chose option 2";
break;
case 3:
cout << "You chose option 3";
break;
default:
cout << "value unknown";
}
return 0;
}
After the user enters 1 and the program enters the switch...case, the user is again asked for the file name. But, this time the program does not wait for a response.
Why is getline() not working the way it would outside the switch...case structure?
Any suggestions would be greatly appreciated.
cin leaves the newline character (\n) in the stream. cin.ignore() extracts and discards characters. It can be used to flush the cin until \n is reached.
So, the solution is to add std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); , before the 2nd call to getline(cin, fileName);
Also add cin.clear() to remove the error flag on cin
Example:
case 1:
{
std::string fileName;
std::cout << "Enter the name of the file including the path" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(std::cin, fileName);
break;
}
The problem might be, that you are reading the number of the case via >> into the integer variable. By doing that, the newline produced by the enter key is still in the buffer. Now getline tries to read from the input stream and instantly receives a newline.
And because it only reads upon the next newline, it exits.
The problem has nothing to do with the switch-statement! Instead, it has to do with mixing formatted input (using operator>>()) and unformatted input (in this case std::getline()): the formatted input stops reading as soon as a character doesn't match the format. When reading an integer, it stops as soon as a non-digit is found. That is, any newline entered after the number will be stuck in the stream and std::getline() will happily take this newline as an opportunity to stop its input.
When switching between formatted and unformatted input, you normally want to get rid of whitespaces. For example, you could use
if (std::getline(std::cin >> std::ws, fileName)) { ... }
to first skip any whitespace, then attempt to read fileName and, if this is successful, process the input (input always needs to be checked for success).
You are mixing formatted input and line input on a single stream. This is a bad idea, use either formatted input operator>> or line input std::getline() never both on the same stream.
This is basically because of the way white space is handled. In this case you are leaving a \n character on the input when you read the option.
cin >> option;
This reads the option, but leaves anything after the option (after the integer) on the input stream (including the \n character). Thus the next use of std::getline() simply reads upto the \n character (which probably gives you zero characters).
Interactive user input is line based.
Especially since the std::cin stream is buffered (and thus not flushed until you hit return).
So when I read input from an interactive user I always read a line of text at a time. Then parse this line for what I am looking for.
std::string optionLine;
std::getline(std::cin, optionLine);
int option = boost::lexical_cast<int>(optionLine);
Note: You don't need boost::lexical_cast, you can achieve the same affect with std::stringstream and another variable.
// A simple alternative to boost::lexical_cast
// Not quite as pedantic as above but you can add more tests as required.
std::stringstream optionLineStream(optionLine);
int option;
if (optionLineStream >> option)
{
// reading the option worked.
}
Reading a line at a time and then parsing the input also has the advantage that you never put the input into a bad state and need to reset it (any bad state is set on intermediate std::stringstream objects). So fixing erroneous user input is easier.

cin.getline not executing c++

For some weird reason my input line cin.getline(oneLine, 80); is completely ignored when I put it in this else if block. I can't understand why because when I move it somewhere else in the program, it works.
else if (choice == "user-id")
{
cout << endl << "Enter a full name e.g. John Smith ";
char oneLine[80];
cin.getline(oneLine, 80);
cout << oneLine;
}
Here's the rest of my code. I'm new to C++ so I'm sure a lot of my conventions may be questionable at best.
int main( )
{
while (true)
{
int pause;
string choice = "proceed";
string nameGiven;
string userIdGiven;
string result;
using namespace std ;
while ((choice != "name") && (choice != "user-id"))
{
cout << "Would you like to search for a name or user-id? ";
cin >> choice;
if ((choice != "name") && (choice != "user-id"))
cout <<"Please enter a valid choice (name or user-id)" << endl;
}
if (choice == "name")
{
string dataType = "int";
while (true)
{
cout << endl << "Enter a valid user id (4 digit maximum) ";
cin >> userIdGiven;
if (valid(userIdGiven))
break;
else
cout << endl << "Not a valid number. " << endl;
continue;
}
result = findData(userIdGiven, dataType);
cout << "name: " << result;
}
else if (choice == "user-id")
{
cout << endl << "Enter a full name e.g. John Smith ";
char oneLine[80];
std::getline(oneLine, 80);
cout << oneLine;
}
string ans;
cout << endl << "Would you like to play again? (yes/no) " << endl;
cin >> ans;
if ( (ans == "yes") || (ans == "Yes") || (ans == "Y") || (ans == "y") )
continue;
else
break;
cin >> pause;
}
return 0;
}
Your std::cin object is in a bad state (std::cin.good() == false) from a previous input operation. For example, you might have tried to read a number, but there were only nun-numeric characters in the input buffer.
Always check for input success before continuing using a std::istream.
Note: Don't use the old input functions operating with char*, as they are more complicated and less safe to use than the new ones operating on std::string. In your case, use std::getline(std::istream&, std::string&, char = '\n').
twsaef's comment's substantively correct... you're streaming a string into choice, which consumes the characters up until but excluding the next whitespace character - you're probably typing a newline to terminate your input, so it's left in the buffer. Then you use getline which sees that newline and reads an empty string.
Easiest solution is to call getline() to read the initial string too, then check if choice is "name\n" or "user-id\n". Better - write a "trim" function to remove the whitespace from the line before comparison (boost string library has this already). Otherwise, you could use read and ignore characters from std::cin until you get a '\n'. Or even read a line then put in into a stringstream and read a string from there.... Lots of choices.
And, please check your stream state! Try to use:
if (std::cin >> x)
// x was parsed from stream... use it
else
// print an error so you know where things failed!
FWIW, I guessed what the problem would be (it's stupidly common) before seeing the update, and chuckled to myself at the other guesses (although they make very good points even if they missed the OP's problem).
The line of code is working correctly and as advertised. It doesn't happen to be working the way you want it to.
When you read from std::cin, that does not pause the program and wait for input. What causes the pause is the lack of sufficient input data for the read operation.
Input is fed to your program a line at a time. Remember, the console window is a program, too. It is responsible for translating the user's key-presses into text characters (bytes, really), handling things like the backspace key, and gathering it all up into lines.
So say you read an int with operator>>, and then read a line with getline. The program will not see an int until the user hits the Return key, because that triggers the console to feed a line of input to your program.
operator>> will skip leading whitespace, read the integer, and leave trailing whitespace alone. Newline characters are whitespace. There is a newline character in the input (at the end of the line, obviously).
getline() will not skip any leading whitespace, and read until the next newline. The very next character happens to be a newline, so getline() happily reads an empty line and the program proceeds with that.
So how do you fix that? Chances are, if you're reading all your input from cin, that you want the program to pause every time you come to a reading operation. The way to do that is to ensure that there is never any available data at that point, and the way to do that is to read everything that's available - i.e., the whole line - every time that you read something.
So, always read a full line from cin. As noted by wilx, please use the free function std::getline for this. Do not use the .getline member function of the stream. Use std::string to represent strings of text. That's what it's there for. It will make your life much, much easier. That also means that if you're expecting an integer and the user types "76 trombones", you get rid of the "trombones" data (and can decide whether you want to just throw it away, or yell at the user and make him re-enter a number without any funny commentary).
But then what? You just have a string, where you may have wanted an int. Fortunately, there is a simple solution for that. We can treat the string as a source of stream data, using the standard library class std::stringstream. We just construct a stringstream from the string, and then use it just like std::cin - i.e. we can read from it with operator>>, check the stream state to see if reading was successful, etc.
As noted by sbi, always check whether reading succeeded! If you try to read an int and the stream contains text like "hi mom", then (a) the int variable will not be altered (so if it was uninitialized it is still uninitialized, a very dangerous state to be in), and (b) the stream will go into a "failed" state and will not read any more until you clear it, and (c) even if you clear it, the data will still be there, which can trigger an infinite loop if you're not careful.
Fortunately, with the separate stringstream, we avoid all kinds of complications. If reading fails, then all those things happen to the stringstream object - not to std::cin. The getline operation will always succeed on std::cin unless perhaps the user explicitly indicates an end-of-file (control-D character on Linux, or control-Z on Windows). We can easily check if the stringstream is in the failed state, loop and just create another one - the old one will automatically get cleaned up.
We can even make a helper function like:
template <typename T>
// Attempt to read into to_read, and return whether successful.
bool read_primitive_from_input(std::istream& input, T& to_read) {
std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
return iss >> to_read;
}
std::stringstream is provided by the standard library header <sstream>. std::string comes from <string>, of course.

How to signify no more input for string ss in the loop while (cin >> ss)

I used "cin" to read words from input stream, which like
int main( ){
string word;
while (cin >> word){
//do sth on the input word
}
// perform some other operations
}
The code structure is something like the above one. It is compilable. During the execution, I keep inputting something like
aa bb cc dd
My question is how to end this input? In other words, suppose the textfile is just "aa bb cc dd". But I do not know how to let the program know that the file ends.
Your code is correct. If you were interactively inputting, you would need to send a EOF character, such as CTRL-D.
This EOF character isn't needed when you are reading in a file. This is because once you hit the end of your input stream, there is nothing left to "cin"(because the stream is now closed), thus the while loop exits.
As others already answer this question, I would like add this important point:
Since Ctrl-Z on Windows (and Ctrl-D on unix systems) causes EOF to reach, and you exit from the while loop, but outside the while loop you cannot read further input, since the EOF is already reached.
So to enable reading using cin again, you need to clear eof flag, and all other failure flags, as shown below:
cin.clear();
After doing this, you can start reading input using cin once again!
int main() {
string word;
while (cin >> word) {
// do something on the input word.
if (foo)
break;
}
// perform some other operations.
}
Hit Ctrl-Z (Ctrl-D on *nix systems) and hit enter. That sends an EOF and invalidates the stream.
cin >> some_variable_or_manipulator will always evaluate to a reference to cin. If you want to check and see if there is more input still to read, you need to do something like this:
int main( ){
string word;
while (cin.good()){
cin >> word;
//do sth on the input word
}
// perform some other operations
}
This checks the stream's goodbit, which is set to true when none of eofbit, failbit, or badbit are set. If there is an error reading, or the stream received an EOF character (from reaching the end of a file or from the user at the keyboard pressing CTRL+D), cin.good() will return false, and break you out of the loop.
I guess you want to jump out at the end of file.
You can get the value of basic_ios::eof , it returns true at the end of stream.
Take the input from a file. Then you will find that the while loop terminates when your program stops taking input.
Actually cin stops taking input when it finds an EOF marker. Each input file ends with this EOF marker. When this EOF marker is encountered by operator>> it modifies the value of internal flag eofbit into false and consequently the while loop stops.
It helps me to terminate loop by hitting ENTER.
int main() {
string word;
while(getline(cin,word) && s.compare("\0") != 0) {
//do sth on the input word
}
// perform some other operations
}
You can make a check for a special word in input.
F.e. "stop":
int main( ){
string word;
while (cin >> word){
if(word == "stop")
break;
//do sth on the input word
}
// perform some other operations
}
you can try this
string word;
vector<string> words;
while (cin >> word) {
words.push_back(word);
if (cin.get() == '\n')
break;
}
in this way, you don't have to end with CTRL+D(Z). program will quit while sentence end
your program doesn't take in count white spaces. make difference between cin and getline...
here is an example with a trick: the program get input and prints output until you hit twice Enter to quit:
#include <iostream>
#include <string>
using namespace std;
int main(){
char c = '\0';
string word;
int nReturn = 0;
cout << "Hit Enter twice to quit\n\n";
while (cin.peek())
{
cin.get(c);
if(nReturn > 1)
break;
if('\n' == c)
nReturn++;
else
nReturn = 0;
word += c;
cout << word;
word = "";
}
cout << endl;
return 0;
}

Infinite loop on EOF in C++

This code works as desired for the most part, which is to prompt the user for a single character, perform the associated action, prompt the user to press return, and repeat. However, when I enter ^D (EOF) at the prompt, an infinite loop occurs. I am clearing the error state via std::cin.clear() and calling std::cin.ignore(...) to clear the buffer. What could be causing the infinite loop?
#include <iostream>
#include <limits>
void wait()
{
std::cout << std::endl << "press enter to continue.";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.clear();
std::cin.get();
}
int main()
{
char response;
while (true)
{
std::cout << "enter a character at the prompt." << std::endl << "> ";
std::cin >> response;
switch (response)
{
case 'q':
exit(0);
break;
}
wait();
}
}
I am running this in the Mac OS X terminal, if it matters.
UPDATE: What I am really asking here is, when the user enters EOF (^D) at the prompt, how do I (a) detect it and (b) reset the stream so that the user can continue to enter data.
The following example is different from the code above, but illustrates the same principle of clearing the stream after a ^D has been detected and continuing to read from that stream.
> a
you entered: a
> b
you entered: b
> ^D
you entered EOF
> c
you entered: c
...
You should always check whether any of a stream's failure flags are set after calling formatted extraction operation, in your example you are checking response without checking whether response was correctly extracted.
Also, you are using std::endl in your prompt output where it doesn't make sense. std::endl prints \n and then flushes the buffer, but you then immediately print more characters so the flush is redundant. As cin and cout are (usually) tied, calling an input function for std::cin will cause std::cout to be flushed in any case so you may as well put a \n into your prompt string and save on the verbose extra << operators.
Why not make a prompting function that prints the prompt, retrieves the input an returns a reference to the stream so that you can test it for success using the usual stream to boolean type conversion.
This way you can get rid of the while true and explicit break.
std::istream& prompt_for_input( std::istream& in, std::ostream& out, char& response )
{
out << "enter a character at the prompt.\n> ";
in >> response;
return in;
}
int main()
{
char response;
while ( prompt_for_input( std::cin, std::cout, response ) && response != 'q' )
{
wait();
}
}
The question does not really make sense for standard input. It will be hard to read something from standard input after that stream has ended -- you'll have to re-open it somehow, but there is no way to re-open standard input. It might be connected to a pipe, or to a file, or to a terminal -- and there's no behaviour suitable for all of these.
So you're going to be reading explicitly from the terminal, I assume. On UN*X systems, that means reading /dev/tty, and re-opening it when needed. Here's a simple example that does it; most error-checking omitted.
// Warning: UN*X-specific
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
for(unsigned i=0; ; i++) {
ifstream tty("/dev/tty");
if (! tty) {
cerr << "Failed to open TTY" << endl;
return 2;
}
string s;
while (getline(tty,s))
cout << i << ": " << s << endl;
}
return 0; // (unreached)
}
You'll need to clear the flags to get the stream to do much of anything after it encounters EOF.
Err, I may be missing something, but I don't ever see you break out of the while (true) loop.
// ...
while (true) {
if (std::cin.eof()) {
break;
}
// ...
}
Upon reading an EOF, you just ignore it and loop back, without exiting the loop, so you'll continually read the EOF and continually loop. If you want to do something on seeing an EOF, you need to handle it either in your switch or before.
Perhaps you want to read input from somewhere after the user has closed your stdin with ^D? In that case, you'll have to close cin and reopen it to read from the other place you want to read input from.
As mentioned, you need to make sure the stream is not in a bad state. I would change while condition to use good(). Don't just check EOF as there are several ways a stream can become "bad" other than EOF.
while (std::cin.good()) {...
while ((std::cout << "Enter a character at the prompt ")
&& (!(std::cin >> response) || response =='q')) {
std::cout << "Not a valid input";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}