Getline problem [duplicate] - c++

This question already has an answer here:
What am I not understanding about getline+strings?
(1 answer)
Closed 7 years ago.
I've got following code:
system("CLS");
string title;
string content;
cout << "Get title." << endl;
getline(cin,title);
cout << "Get content." << endl;
getline(cin,content);
The problem is - application is not asking about tittle, I've got Get title, get content and then waiting for user input, it's not waiting for user input after get title.bDo I have to add any break or smth?
Or maybe, that isn't the best idea to read whole text line from user input?

If you have a cin >> something; call prior to your system() call.
For example, taking input into an integer. When cin >> myintvar; (or similar) then the integer is placed in myintvar and the '\n' gets sent along in the stream. The getline picks the \n up as indicative of the end of a line of input, so it is effectively "skipped".
Either change the cin >> to a getline()
or call cin.ignore() to grab the '\n'(or better, call a cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n' ); to flush the input buffer-- but be sure you're not throwing away valuable input in the process).

I'd bet that you have something like a menu for selecting options ( as a numeric type ) and after that you try to read the lines.
This happens because after std::cin read some value the remaining '\n' was not processed yet, the solution would be to include #include <limits> and then put std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
before your getline(cin,title);

It is because when you use getline() it ignores the newline at the end of the line and feeds it into the input queue, so when your getline function is called for next time it encounters the newline character discarded by the previous getline() and so it considers that as end of your input string. So thats why it doesn't take any input from you. You could use something like this
getline(cin,title);
cin.get();
hope this works.

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

cin.get() isn't working as it should [duplicate]

This question already has an answer here:
Cin.get() issue with C++ [duplicate]
(1 answer)
Closed 9 years ago.
First, here is the code:
using namespace std;
cout << "\aOperation \"HyperHype\" is now activated!\n";
cout << "Enter your agent code:_______\b\b\b\b\b\b\b";
long code;
cin >> code;
cin.get();
cout << "\aYou entered " << code << ".....\n";
cout << "\aCode verified! Proceed with Plan Z3!\n";
cin.get();
return 0;
It compiles without a problem and runs almost without flaw; after 'code' receives its value from standard input, the final string flashes up for maybe a millisecond and the program dies. As you can see I placed the 'cin.get()' member function after the final string in order to prevent this, yet it continues to die after the 'cin >> code;' line.
This method has worked for all of my other practice programs up until now, and there is nothing structurally different between this program and any of the others.
Any suggestions?
(Assume proper header files and preprocessor directives are in place.)
You are reading the newline character you already entered earlier with your final get() call. You might want to ignore all characters up to and including the first newline before waiting for some other input:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
You can shorten this to become
std::cin >> std::ws;
if it is OK requiring to enter a non-whitespace character to terminate the program: the std::ws manipulator extracts whitespace characters until either a non-whitespace character or the end of the stream is reached.
Note that std::istream::get() actually does work as it should! It just reads the next character. It just happens not to do what you did expect.
Add a cin >> code line instead of the two cin.get(). If the program just closes anyway, then this would probably be the simplest thing to do.

C++ Press Enter to Terminate Program [duplicate]

This question already has answers here:
Cin.Ignore() is not working
(4 answers)
Closed 9 years ago.
I am writing a C++ program and I need to program to end/terminate after the user hits enter.
This is what I have:
cout << "Press Enter to End" << endl;
cin.ignore(); //ends after the user hits enter
return 0;
But it doesn't work. Any advice?
I sense that you had some formatted input earlier in your program, i.e., it looks something like this:
std::cin >> value;
do_something(value);
std::cout << "press enter to end\n";
std::cin.ignore();
If that is the case, you have some character in the input buffer from the time you entered value. For example, there can be a '\n' but it can be any odd other characters, too. This character will be read when the program encounters std::cin.ignore().
What you probably want to is to get rid of the characters currently known to be in the buffer. This isn't quite what would be done as this can still miss characters which are already entered but not, yet, transferred but there is no portable approach to clear all potential characters (it is normally not a problem because hardly any user interface depends on character input from a terminal).
To ignore the characters which are known to be present you need to start off by breaking the connection between <stdio.h> and IOStreams using std::ios_base::sync_with_stdio() and later consume the known characters entered after your last read, e.g.,
#include <iostream>
int main()
{
std::ios_base::sync_with_stdio(false);
int x;
std::cin >> x;
std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cout << "press enter\n";
std::cin.ignore();
}
The odd call to sync_with_stdio() is necessary to have the IOStreams actually buffer the characters received from the system rather than reading characters individually. As a nice side effect it dramatically improves the performance of using std:cin, std::cout, and the other standard stream objects.
maybe add system("pause") in the end of code; (include first). I guess you want enter to close termination.

getline() does not work if used after some inputs [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Need help with getline()
getline() is not working, if I use it after some inputs, i.e.
#include<iostream>
using namespace std;
main()
{
string date,time;
char journal[23];
cout<<"Date:\t";
cin>>date;
cout<<"Time:\t";
cin>>time;
cout<<"Journal Entry:\t";
cin.getline(journal,23);
cout<<endl;
system("pause");
}
where as if I use getline() on top of inputs, it does work i.e.
cout<<"Journal Entry:\t";
cin.getline(journal,23);
cout<<"Date:\t";
cin>>date;
cout<<"Time:\t";
cin>>time;
What might be the reason?
Characters are extracted until either (n - 1) characters have been
extracted or the delimiting character is found (which is delimiter if this
parameter is specified, or '\n' otherwise). The extraction also stops
if the end of the file is reached in the input sequence or if an error
occurs during the input operation.
When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() before calling getline().
cout<<"Journal Entry:\t";
cin.ignore();
cin.getline(journal,23);
Adding to what #DavidHammen said:
The extraction operations leave the trailing '\n' character in the stream. On the other hand, istream::getline() discards it. So when you call getline after an extraction operator, '\n' is the first character it encounters and it stops reading right there.
Put this after before getline call extraction:
cin.ignore()
A more robust way of taking input would be something like this:
while (true) {
cout<<"Time:\t";
if (cin>>time) {
cin.ignore(); // discard the trailing '\n'
break;
} else {
// ignore everything or to the first '\n', whichever comes first
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear(); // clear the error flags
cout << "Invalid input, try again.\n";
}
}
You're not checking stream status. The std::cin stream extraction operator (operator>>) can fail. When it does, the stream is marked as "bad" (failbit, badbit, or eofbit are set). Once "bad", all subsequent stream extractions on that stream will fail unless you clear the status.
Learn to be a paranoid programmer. Always check status of those formatted input operations. You could, for example throw an exception, or print an error message and exit. The one thing you shouldn't do is to simply assume that it worked.

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.