Problems looping in C++ with \n - c++

What I am trying to do is make a while loop that loops as long as "\n" is not entered. The problem is that it asks for my input once and then just ends. Here is my code
paliTester = cin.get();
while (paliTester != "\n")
{
paliTester = cin.get();
}

The problem is not with your code, the problem is with the console that is providing you with your input. All consoles today provide a line editing option. Meaning you can type a command, erase part of it and rewrite as many times as you want. Until you'll press ENTER no input will be provided to the program waiting to read it. This means there's no way to provide any content to your program without pressing ENTER and ENTER means your program will receive '\n'.

Probably because \n is the new line escape sequence. Use "\\n" instead.
Also try this instead of get().
cin >> paliTester;
while (paliTester != "\\n")
{
cin >> paliTester;
}

Related

Ending a while loop in command prompt

This is an excerpt from the Competitive Programmer's Handbook by Antti Laaksonen:
If the amount of data is unknown, the following loop is useful:
while (cin >> x) {
// code
}
This loop reads elements from the input one after another, until
there is no more data available in the input.
My question is how do we end such a loop in the command prompt, where the prompt takes one input at a time? By pressing enter, the prompt asks for new input and not terminating the input.
Edit: I have tried using ctrl + D/Z but I am getting this:
In order for that loop to end, cin needs to enter a failed state. That will cause it to evaluate to false and stop the loop. You have a couple ways you can do that. First is to send bad input, which will cause cin to fail and end the loop. Since you are excepting integers, you could just input a letter and that will cause it to break.
Another option is to send the EOF (end of file) signal to cin You can do that using ctrl+D (windows) or ctrl+Z (linux) and the pressing enter. cin will stop reading once it sees it has reachged the EOF and it will enter a failed state and cause the loop to end.
It should be noted that with both of these options that if you want to use cin again after you do this you will need to call clear() to remove the error flags and if you entered bad input, you will need to use ignore() to remove the bad input from the stream.
My question is how do we end such a loop in the command prompt, where the prompt takes one input at a time?
Note that cin >> x; returns cin. This means when you write
while(cin >> x)
you do the >> operation into x and then check cin.
When the user enters an input whose type differs from the type of variable x, then this while loop will end automatically. This is because cin will not be in a valid state anymore and hence cin >> x will become false . Basically the loop ends when the state of the stream is set to failed. Like supplying a different type value or when EOF is encountered.
There is other way to end such a loop from inside the while block by using break .

c++ string.compare don't accept space characters

First I want to apologist about my bad title. Now the problem. I'm trying to compare two strings in C++. I had try with string.compare and ==, none of them worked. Here is code
if(game_type == "AI vs AI"){
std::cout<<"You choosed AI vs AI\n";
aiVsAI(range);
}
else{
std::cerr <<"Error";
}
and with string.compare
if(game_type.compare("AI vs AI") == 0){
std::cout<<"You choosed AI vs AI\n";
aiVsAI(range);
}
else{
std::cerr <<"Error";
}
If I give AIvsAI for input the program works correctly, but if i enter AI (space) vs (space) AI, the program prints "Error". I tried using \x20 instant of space but this didn't work too. Any ideas why this is happening?
It appears that you are using a statement similar to
std::cin >> game_type;
to obtain the user input. The problem is that the >> operator only extracts the first word from the line the user types, which makes game_type only contain AI when you type AI vs AI. (As a side note, if you were to use std::cin >> blah on the next line, then blah would contain vs because that typed input had not been consumed yet.)
To fix this, you can use std::getline:
std::getline(std::cin, game_type);
This gets everything the user types on the line (up to but not including the Enter keypress) and puts that in game_type. This is almost always the right way to get user input for an interactive program.

Meaning of cin.fail() in C++?

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/

Run Time Error: Program skipping prompt for second and third names [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Program is skipping over Getline() without taking user input
Alright, so I have a program that is running and at the start it prompts you for the data fill the data members. The program does this for 3 different objects.
My problem is that, at run time, after inputting data for the fist object the program proceeds to skip input for the second name and goes straight to the next option. It does the same thing for the third option's name. It also does this when you get the chance to change the data.
"Enter CD Name: Microsoft Word
1-Game
2-Word
3-Compiler
4-Spreadsheet
5-Dbase
6-Presentation
Enter the number that corresponds with the CD's Type: 2
Input CD Cost: 15.23
Enter CD Name: 1-Game <- ((Skips the input part and takes you directly to the menu!))
2-Word
3-Compiler
4-Spreadsheet
5-Dbase
6-Presentation
Enter the number that corresponds with the CD's Type:"
The issue is most likely in my member function, but I'm not sure what the issue is.
Here's my member function code:
void CDX::LoadInfo() //Prompts, validates and sets data members
{
cout << "Enter CD Name: ";
getline(cin, Name);
int choice=0;
do
{ cout << "1-Game\n2-Word\n3-Compiler\n4-Spreadsheet\n5-Dbase\n6-Presentation" << endl;
cout << "Enter the number that corresponds with the CD's Type: ";
cin >> choice;
} while ((choice <1)||(choice>6));
switch(choice)
//Code for case-switch statement goes here)
So what am I missing? Is this a buffer issue or am I prematurely ending the code in some way that causes it to skip?
The conversion of a number stops when it finds a character that can't be converted.
In that case, the character is '\n'
When you use getline to read a line, this character is read and discarded, but when you read a number, it is read (to know if the number continues or not) and if it is not part of the number, it is left in buffer for the next read.
Example:
If you write:
"29312"
and press enter, your buffer will be filled with
"29312\n".
If you use cin >> number, to read stdin, it will consume the digits, but will left in the buffer the "\n".
In the next time you call getline, it will read an empty line that was left in the buffer.
I think it's because the first 'getline(cin, Name)' gobbles up the last newline keypress. When you enter the cost and press ENTER, the call to getline is completed.
You can keep an extra getline after taking the cost so that it consumes the newline. Then, I think, it will run correctly.
You have read the "CD Cost", but the newline remains in the input buffer. Skip whitespace before reading the CD name:
ws(cin);

Trying to Read a Line of Keyboard Input in C++

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.