I have a program that takes two numbers and shows them on the screen.
However, when I hit "enter" after I input the first number, my program shows the answers before letting me input the second number.
Why does this happen?
int main()
{
int n1;
float n2;
cin>>n1;
cin>>n2;
cout<<"int n:"<<n1<<endl<<"float n:"<<n2;
return 0;
}
I wanna input 0.25 and 35 but when I write 0.25 and hit enter suddenly shows the answer "int: n:0 float n:0.25" it doesn't let me write second num. my os is Win10 and this program compiled with DevCpp
It works when both variables are ints.
There is no difference between cin>>n1; cin>>n2; and cin >> n1 >>n2. Enter key only serves as signal to sychronize input buffer and stream buffer. cin doesn't input per line, it parses buffer when there is available volume of data. If parse incomplete, it waits. If parse can't be done, it stops and state bit changes. To continue parsing you have either ignore or clear part or whole buffer content.
Something wrong was entered in first line, causing cin to go into bad() state. Edge case might happen if you're running program through a remote terminal, some incorrect character could slip in, e.g. ^M generated by new line from Windows would break cin stream on Linux. That's also case if you input from a file which was saved on different platform. On Windows line ends consist of two characters, #10 and #13. On linux steams expect only #13 as a new line and buffer flush signal, #10 is an unexpected character.
Edit (after OP gave information about input data):
"0.25" would be parsed as "0" and ".25", that expected and documented stream behavior. Parsing for n1 had stopped as soon as stream encountered character which doesn't fit int pattern, which could be space, end of line, alphabetic or punctuation. Period considered a punctuation in this case
Then it tries to get a float from stream input and buffer contains ".25". It's a legal float notation and it gets assigned to n2.
When you have both "int", you cannot get second value at all with same input, it always will be 0, because cin locks up in bad state, i.e. method its istream::good() returns false. You have to check state of stream after reading variables. Any further formatted reading that wouldn't be able to parse .25 wouldn't advance stream past that point.
If you want to read from stream exclusively line by line, you have to use istream::getline() method to get the string. There is also method get which can acquire content of stream and ignore which allows to discard part of stream.
Related
Referring to two questions:
Incorrect output from C++ Primer 1.4.4
Confused by control flow execution in C++ Primer example
My question is answered in both of those posts, but I want to delve further.
First, I know this is only the beginning, but let's say I make a fully functional program that runs in a designed window. By that level, will I already know how to implement a EOF? I can't expect someone running my program to know that they need to hit Control-Z.
Is there a way to implement a specific code that functions so that it does not need me to type in an unrecognized value?
Also one guy in those questions somewhat answered the importance of EOF, but how come the program doesn't even post the final cnt - 1?
Let's say I do the numbers 10 10 10 20 20 20. Without EOF, this will only show the "10 repeats 3 times." How come the program doesn't at least type in the count "10 repeats 3 times and 20 repeats 2 times" minus the final one with white space?
lets say I make a fully functional program that runs in a designed window. By that level, will I already know how to implement a eof? I can't expect someone running my program to know that they need to hit ctrl + z.
You could either tell the user explicitly to do a specific action to end input or the design of the window itself could tell the user the information implicitly. For instance, a dialog box could ask the user to enter input and click an OK button when done.
Is there a way to implement a specific code that functions so that it does not need me to type in an unrecognized value?
It seems like you would rather use a newline character to terminate your input. An example of this usage could be std::getline. Instead of writing
while (std::cin >> val)
you could instead use
std::string line;
if (std::getline(std::cin,line))
and assume that your user's input only consists of one line of values. There are plenty of other ways to similarly achieve this task depending on how you want to constrain the user's input.
Let's say I do the numbers 10 10 10 20 20 20. WIthout eof this will only show the "10 repeats 3 times." How come the program doesn't at least type in the count "10 repeats 3 times and 20 repeats 2 times" minus the final one with white space?
Without the eof your program is still executing the while (std::cin >> val) loop since std::cin >> val has not yet received invalid input.
Since the line
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
occurs after that while loop finishes execution, you don't (yet) see any information about the three 20's in the input.
When you are reading a sequence of inputs you'll need some indication when your down. That could be a sentinel value ("enter 999 to stop reading"; you'd need to detect that while reading), an invalid input ("enter X to stop reading"; when reading an int the value X is illegal and causes the stream to got into failure mode, i.e., have std::ios_base::failbit set), or the more conventional "there isn't anything more to read". For a file, the last conditions is straight forward. When reading data from the console you'll either need to teach people how to terminate the input or you'll need to use a different approach.
If you want to intercept any keypressed and react on them directly you may do so, too. You could, e.g., use ncurses and control your input via that. You could also set the concole to non-buffering (on POSIX systems using tcgetattr() and tcsetattr() to clear the ICANON flag) and deal directly with all key presses to decide whether you want to continue reading or not.
Although I'm certainly up to doing fancy I/O stuff I normally don't bother: users will understand the "end of input" character and just deal with it. That is, my input normally looks something like this:
while (in >> whatever_needs_to_be_read) { ... }
... or, if the input is genuinely line oriented
for (std::string line; std::getline(in, line); ) { ... }
The function doing this input will then be called with a suitable std::istream which may be std::cin although I have typically some way to also read from a file (in addition to the shell-privided input redirection).
BTW, despite some indications in the questions referenced, "EOF" is not a character being read. It is a character entered, though (normally). ... and it is quite conventional to "know" the end of input character (on POSIX systems a ctrl-D and on Windows a ctrl-Z). You can use other indicators, e.g., the "interrupt" (ctrl-C) but that takes more work and doesn't integrate nicely with stream. To use the interrupt chacter you'd need to setup a signal handler for SIGINT and deal with that. One slightly annoying part of doing so is that if you get it wrong you'll need to find a different way to kill the program (e.g. on POSIX using ctrl-Z to put the process to sleep and kill it via a harsher signal).
Could seem an old question, but the problem here isn't the use of TWO cin.get(), but of more than two! if I write (in DEV C++)
I get just one input request (s) and then end program. Now, I expected having at least two request of cin, because I expected:
char s[50];
char t[100];
char r[100];
char f[100];
cin.get(s,49);
cin.get(t,99);
cin.get(r,99);
cin.get(f,99);
I expeted at least 2 input request, because:
first cin: buffer empty,I insert the string s and \n
second cin: I have in buffer \n still, then t=\n without input request
third cin: buffer empty, I insert the string r and \n
fourth cin: I have in buffer \n still, then f=\n without input request
But I have just the input request for s string!
why have I just one input request?the buffer didn't clean with second cin.get, letting third cin.get work properly? Thanks
t does NOT equal '\n'. It's empty. .get(char*,int) will never remove the '\n' from the buffer.
Worse, the attempt to read to t will set cin to a fail state since nothing could be read, which will cause all subsequent reads of any sort from cin to fail immediately without even trying until you .clear() the fail state.
This is surprising behavior, but you seem to have already guessed at most of it as per your last sentence in the question, so, Good Job! You're learning!
http://en.cppreference.com/w/cpp/io/basic_istream/get
while (!correct)
{
cout << "Please enter an angle value => ";
cin >> value; //request user to input a value
if(cin.fail()) // LINE 7
{
cin.clear(); // LINE 9
while(cin.get() != '\n'); // LINE 10
textcolor(WHITE);
cout << "Please enter a valid value. "<< endl;
correct = false;
}
else
{
cin.ignore(); // LINE 18
correct =true;
}
}
Hi, this is part of the code that I have written.
The purpose of this code is to restrict users to input numbers like 10,10.00 etc,
if they input values like (abc,!$#,etc...) the code will request users to reenter the values.
In order to perform this function( restrict user to input valid valus), I get some tips and guides through forums.
I think is my responsibility to learn and understand what these codes do... since this is the first time I use this code.
can someone briefly explain to me what does the codes in
line 7,9,10, and 18 do? Especially line 10. I got a brief idea on others line just line 10 I don't know what it did.
Thanks for your guides, I appreciate that!
cin.fail() tells you if "something failed" in a previous input operation. I beleive there are four recognised states of an input stream: bad, good, eof and fail (but fail and bad can be set at the same time, for example).
cin.clear() resets the state to good.
while(cin.get() != '\n') ; will read until the end of the current input line.
cin.ignore(); will skip until the next newline, so is very similar to while(cin.get() != '\n');.
The whole code should check for end of file too, or it will hang (loop forever with failure) if no correct input is given and the input is "ended" (e.g. CTRL-Z or CTRL-D depending on platform).
// LINE 7: cin.fail() detects whether the value entered fits the value defined in the variable.
// LINE 18: cin leaves the newline character in the stream. Adding cin.ignore() to the next line clears/ignores the newline from the stream.
For line 7 and line 9, read the document.
while(cin.get() != '\n'); // LINE 10
in the while, it tests whether the line cin.get() is an empty line, i.e, containing just the new line.
Line 7: test if entered data is correct (can be read as decltype(value)). cin.fail() is always true if some error with the stream happened. Later, in
line 9: you clear cin state from bad to previous, normal state. (recover after the error). You cannot read data anymore until recovering from the bad state.
Line 10: you read until the end of line. Basically you skip one line from the input
Line 18: this line executes only if entered data is corrected. It reads and discards one line from stdin.
while(cin.get() != '\n'): All string in c are null terminated. This means that \n is the end of all the string objects. Lets say you have string "this" for c it is this\n, each alphabet being stored in a char type. Please read along
http://www.functionx.com/cpp/Lesson16.htm
cin.fail(): cin.fail() detects whether the value entered fits the value defined in the variable.
read:http://www.cplusplus.com/forum/beginner/2957/
cin.ignore(): Extracts characters from the input sequence and discards them
http://www.cplusplus.com/reference/istream/istream/ignore/
I know it's not usual in Stack Overflow to just list links, so I'll give a bit more detail, but this answer really boils down to a bunch of links.
For line 7, just google cin.fail. Here's a good reference, and what it says:
Returns true if either (or both) the failbit or the badbit error state flags is set for the stream.
At least one of these flags is set when some error other than reaching the End-Of-File occurs during an input operation.
failbit is generally set by an operation when the error is related to the internal logic of the operation itself; further operations on the stream may be possible. While badbit is generally set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is attempted on the stream. badbit can be checked independently by calling member function bad:
One line translation: it tells you if there was an unexpected error while trying to read the input stream.
You can find similar references for cin.ignore, cin.clear and cin.get. The quick summary:
cin.ignore - ignore one single character present in the stream.
cin.clear - clear any error flags in the stream
cin.get - get one character at a time, until you hit the newline '\n' character.
The standard input stream (cin) can fail due to a number of reasons.
For example, if value is an int, and the user enters a large number like
124812471571258125, cin >> value will fail because the number is too big to fit inside an int.
But:
There is a much simpler way to do what you want. You want the user to enter only valid floating-point values, e.g. 10 or 10.00, but no characters, right? So you can just do this:
double value;
cout << "Please enter an angle value: " << endl;
while (!(cin >> value)) { //Since value is a double, (cin >> value) will be true only if the user enters a valid value that can be put inside a double
cout << "Please enter a valid value:" << endl;
}
This does the same thing that your code does, but much more simply.
If you're interested in what other things can cause cin to fail, look here:
http://www.cplusplus.com/forum/beginner/2957/
For some reason in my program when I reach a certain spot, I have to press Enter twice in order to get it to submit. I added the clear to keep it from skipping input and the ignore() to keep it from keeping any extra characters in the buffer. I enter my input and then it drops down to a new line, I hit Enter again and it enter the input and continues the program no problem but I'm wondering why. Here's a code snippet:
cin.ignore();
cout << "Enter Student Major (ex. COSC): ";
cin.getline(student.major, 6);
for(int i = 0; i < sizeof(student.major); i++)
student.major[i] = toupper(student.major[i]);
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Any suggestions?
It seems to me that you are tossing too many cin.ignore() around, not knowing exactly why they are needed and when to put them there.
There are two common circumstances where cin.ignore() is needed to "make input work right":
when mixing formatted and unformatted input;
to recover from a formatted input error.
In both cases, you want to get rid of spurious characters from the input buffer; if there isn't any such character (which is probably what happens in your program), cin.ignore() will pause the execution and wait for user input - after all, you asked it to ignore some characters, and dammit, it will obey to its orders.
(although ignore() by default would "eat" just one character, whatever it may be, the execution is paused until a newline is found because by default cin is line buffered - new input is not examined until a newline is recieved)
Case 1:
cin.ignore() calls are often needed if you are performing an unformatted input operation (like getline) after performing a formatted input operation (i.e. using the >> operator).
This happens because the >> operator leaves the newline in the input buffer; that's not a problem if you are performing only formatted input operations (by default they skip all the whitespace before trying to interpret the input), but it's a problem if afterwards you do unformatted input: getline by default reads until it finds a newline, so the "spurious newline" left will make it stop reading immediately.
So, here you will usually call cin.ignore(...) call to get rid of the newline just after the last formatted input operation you do in a row, guaranteeing that the input buffer is empty. Afterwards, you can call getline directly without fear, knowing that you left the buffer empty.
It's a bad idea, instead, to put it before any getline, as you seem to do in your code, since there may be code paths that lead to that getline that have the input buffer clean, so the ignore call will block.
Case 2:
when istream encounters an error in a formatted input operations, it leaves the "bad" characters in the buffer, so if you retry the operation you get stuck endlessly, since the offenders are still there. The usual clear()/ignore() idiom comes to the rescue, removing the whole offending line from the input buffer.
Again, you don't put the clear()/ignore() sequence at random, but only after you get an input error from a formatted input operation (which sets the failbit of the stream).
Now, aside from these cases, it's uncommon to use cin.ignore() (unless you actually want to skip characters); don't spread it around randomly "just to be safe", because otherwise you will encounter the problem you described.
The answer can be found here.
The extraction ends when n characters have been extracted and discarded or when the character delim is found, whichever comes first. In the latter case, the delim character itself is also extracted.
So in your case, the program will not continue until a '\n' character is received.
I think cin.ignore(numeric_limits<streamsize>::max(), '\n'); is expecting a \n in the input and it doesn't find it, so you have to press Enter again for it to find it.
I mam trying to complete a college assignment in C++ and am having trouble with what should be a very basic operation. I am trying to read a string of characters from the keyboard. This is the relevant code:
string t;
cout << endl << "Enter title to search for: ";
getline(cin, t, '\n');
I understand, that the last line is supposed to read the input buffer (cin , in this instance) and store the character in the 't' string until it reaches a new line character and then continue the program flow.
However, when I run my code in XCode, it just sort of jumps over the getline function and treats 't' as an empty string.
What's going on? I tried using cin >> t but that just read characters forever - Why cant I get this to behave?
The reason that the input operation apparently is skipped, is most probably (that means, ignoring possible peculiarities of a bugsy XCode IDE) that you have performed some input earlier and left a newline in the input buffer.
To fix that, make sure that you have emptied the input buffer after each input operation that logically should consume a line of input.
One easy way is to always use getline into a string, and then use e.g. an istringstream if you want to convert a number specification to number type.
Cheers & hth.,
From the docs page it looks like you want
cin.getline(t,256,'\n');
or something similar.
This sounds like an issue with the way Xcode is running your program. Try running your program directly from the terminal, and see if this is sufficient to fix your issue.