C++ end iteration but not loop [duplicate] - c++

This question already has answers here:
Trying to use a while statement to validate user input C++
(4 answers)
Closed 7 years ago.
There is a loop i want to run and check for valid input, if not valid jump out the itteration and start at the beginning of the loop where i ask for input.
close = false;
int direction
while (!close){
if (!(cin >> direction)){
cout << "not valid: " << endl;
continue;
}
close = true;
}
However when I run it I can only enter the direction one time and not reenter it when continue is reached. How can I end a itteration and let the user retry.
When adding the variable to the while loop and remove from above the while loop (it's local to the while loop and destroyed outside than right?) like
while (!close){
int direction;
////
}
it also dosn't work. I know the whole part of code could be better but I just started with c++ and am trying to understand why it dosn't work like i expect.

Why not use a while loop?
while(! (cin >> x)) {
cout << "invalid input " << endl;
}

Related

How does "while(getline(cin, name))" controls an unknown number of lines of queries? [duplicate]

This question already has answers here:
How does getline() actually behave?
(2 answers)
Closed 2 years ago.
In a problem of HackerRank there is a condition to take an unknown number of lines of queries. The problem's link is:
Day 8: Dictionaries and Maps
I couldn't be able to solve the problem for every test cases, but I looked at the solutions and found that people are using while(getline(cin, name)) to control an unknown number of lines of queries like below:
string name;
while(getline(cin, name))
{
std::map<string, string>::iterator it;
it = phoneList.find(name);
if (it == phoneList.end()){
cout << "Not found" << endl;
} else {
cout << name << "=" << it->second << endl;
}
}
Now, I am not getting how an unknown number of lines of queries are controlled by while(getline(cin, name)).
std::cin is an input stream.
std::getline reads a line from std::cin and writes it to name. It returns the equivalent of true if this has no errors, false otherwise.
The while loop therefore reads lines until it fails or is broken out of.
You can force a fail with std::cin.setstate(std::ios_base::failbit);, or break out of the for loop.

Why am I reading the last word in my file twice? [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 7 years ago.
I'm trying to read in the text from a file and this is what I am doing:
int main(int argc, char* argv[])
{
ifstream inFile;
inFile.open(argv[1]);
string item;
while(inFile.good())
{
inFile >> item;
cout << item << " " << endl;
}
For some reason it will read the last word in the file twice. I tried using a count variable to keep track of how many times it enters the while loop and it always enters one time more then the total number of line in the file. I think this is happening because the inFile.good() statement is not returning false soon enough. How can if fix it?
You are not testing if the
inFile >> item;
Is succeeding -- at the point of having read the last word of the file there is still a newline or some other blank space -- so you have not reached end-of-file, but on the other hand there are no more words to be read either, so the last read fails, but you are not detecting it.
You can test the success of the >> as a bool-expression, this should work;
if (inFile >> item)
cout << item << " " << endl;
The last read fails but you don't catch it. The variable just retains the previous value.
Change your loop to:
while(inFile >> item)
{
cout << item << " " << endl;
}
Other people have shown the code you should have written, so I'm just going to explain why your code didn't work.
istream.good(), indeed, "is not returning false soon enough." It will still be true after you have read the last item in the file. It only becomes false when you attempt to read one item past the end of the file.
All the various ways of asking the question "have I reached the end of the file?" in C and C++ have the same semantics. This is because the underlying OS primitive, read, cannot return data and signal EOF at the same time.

The difference between while and do while C++? [duplicate]

This question already has answers here:
'do...while' vs. 'while'
(31 answers)
Closed 8 years ago.
I would like someone to explain the difference between a while and a do while in C++
I just started learning C++ and with this code I seem to get the same output:
int number =0;
while (number<10)
{
cout << number << endl;
number++
}
and this code:
int number=0;
do
{
cout << number << endl;
number++
} while (number<10);
The output is both the same in these both calculations. So there seem to be no difference.
I tried to look for other examples but they looked way to difficult to understand since it contained mathemetical stuff and other things which I haven't quite learned yet. Also my book gives a sort of psychedelic answer to my question.
Is there an easier example to show the difference between these 2 loops?
I was quite curious
The while loop first evaluates number < 10 and then executes the body, until number < 10 is false.
The do-while loop, executes the body, and then evaluates number < 10, until number < 10 is false.
For example, this prints nothing:
int i = 11;
while( i < 10 )
{
std::cout << i << std::endl;
i++;
}
But this prints 11:
int j = 11;
do
{
std::cout << j << std::endl;
j++;
}
while( j < 10 );
The while loop is an entry control loop, i.e. it first checks the condition in the while(condition){ ...body... } and then executes the body of the loop and keep looping and repeating the procedure until the condition is false.
The do while loop is an exit control loop, i.e. it checks the condition in the do{...body...}while(condition) after the body of the loop has been executed (the body in the do while loop will always be executed at least once) and then loops through the body again until the condition is found to be false.
Hope this helps :)
For Example:
In case of while loop nothing gets printed in this situation as 1 is not less than 1, condition fails and loop exits
int n=1;
while(n<1)
cout << "This does not get printed" << endl;
Whereas in case of do while the statement gets printed as it doesn't know anything about the condition right now until it executes the body atleast once and then it stop because condition fails.
int n=1;
do
cout << "This one gets printed" << endl;
while(n<1);
If you consider using a different starting value you can more clearly see the difference:
int number = 10;
while (number<10)
{
cout << number << endl;
number++
}
// no output
In the first example the condition immeditately fails, so the loop won't execute. However, because the condition isn't tested until after the loop code in the 2nd example, you'll get a single iteration.
int number = 10;
do
{
cout << number << endl;
number++
}
while (number<10);
// output: 10
The while loop will only execute of the conditions are met. Whereas the do while loop will execute the first time without verifying the conditions, not until after initial execution.

Cant cin after terminating the while loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
int n;
while(cin>>n)
cout << n; // Run by the program if received an int value
cout << "Break from loop"; // Run by the program
cin >> n; // Skipped by the program
cout << n; // Run by the program
cant accept another input after terminating the while loop using characters.
How to accept another input if the input within the loop has been terminated using non-integer/floating-point values.
If you are not terminating the program by returning end of file (i.e. Ctrl-D) or terminating the program altogether (i.e. Ctrl-C).
That is, if you exit the loop via incorrect data type, such as typing in the letter d instead of an integer, you can follow the while loop with cin.clear() and getline(cin, str), where str is some string you declare ahead of time.
You should be able to accept input for the second cin at after this.
So,
string str;
int n;
while(cin>>n)
cout << n << endl;
cin.clear();
getline(cin, str);
cout << "Break from loop" << endl;;
cin >> n;
cout << n;
int n;
while(cin>>n) // Keep asking for value to input
cout<<n<<"\n"; // This loop will never terminate for any Supplied val
//Above loop will terminate only when no more valued is supplied to code
// Hence once, we stopped entering the value, code will execute next line
// And end without asking for anymore value.
cout<<"Break From Loop \n";
Assuming your question is "How do I resume input after the stream state has been set?" then there is a simple explanation:
The while loop in which you performed the extraction terminated only until the extraction failed; this also includes when the stream reaches the end of the input stream (EOF). When that happens the eofbit will be set in the steam state (as well as the failbit). A stream can't be used for I/O when its stream state is set. In order to use it again, the stream state must be cleared. This is done using the member function clear(std::ios_base::iostate err = std::ios_base::goodbit).
std::cin.clear();
That call will clear the bits in the stream state and assign them to 0 (std::ios_base::goodbit). After this call the stream can be used for I/O again.
This is assuming the stream read all the characters until it reached EOF. It's not sufficient for a pervious read that terminated upon the acquisition of invalid data. One would also have to ignore() the remaining characters.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

Can you explain HOW bool can control loops?

I'm a beginner programmer in C++ (currently), and I've got a conceptual question.
I'm trying to filter a cin input to ensure that it is a one-or-two-digit integer between 01-04, and if it isn't, to produce an error and ask for a new input.
I'm also using map to give the user a list of options that, upon valid selection, routes inputs (integers) through any of several methods to produce a relevant result, but I'll ask a more specific version of this question elsewhere.
I found a snippet of code at http://www.cplusplus.com/forum/beginner/26821/ that is meant to validate an input. I sort of get it, except where the boolean condition is set inside the while loop. Because I don't understand it, it makes it very difficult to edit or make sure that I'm manipulating it right.
Here is the example code:
int main()
{
int num;
bool valid = false;
while (!valid)
{
valid = true; //Assume the cin will be an integer.
cout << "Enter an integer value: " << endl;
cin >> num;
if(cin.fail()) //cin.fail() checks to see if the value in the cin
//stream is the correct type, if not it returns true,
//false otherwise.
{
cin.clear(); //This corrects the stream.
cin.ignore(); //This skips the left over stream data.
cout << "Please enter an Integer only." << endl;
valid = false; //The cin was not an integer so try again.
}
}
cout << "You entered: " << num << endl;
system("PAUSE");
return 0;
And here is my code (the entire thing, to give context). I don't think it's complete, I just want to make sure I'm using the boolean right.
float _tmain(float argc, _TCHAR* argv[])
{
bool validInput = !true;
map<string,int> Operations;
Operations.insert(pair<string, int>("Addition", 01));
Operations.insert(pair<string, int>("Subtraction", 02));
Operations.insert(pair<string, int>("Multiplication", 03));
Operations.insert(pair<string, int>("Division", 04));
cout << "Welcome to OneOpCalc, what operation would you like to perform?" << endl;
for(map<string, int>::iterator ii=Operations.begin(); ii!=Operations.end(); ++ii)
{
cout << (*ii).second << ": " << (*ii).first << endl;
}
while (!validInput)
{
cin >> operatorSelection;
if (cin.fail() || operatorSelection < 4 || operatorSelection > 1)
{
cout << "Error: Invalid selection. Please choose a valid number." << endl << endl;
cin.clear();
cin.ignore();
}
}
}
Does while (!valid) mean "While valid is false"? In my head, it's saying "While valid is !valid", which obviously, would always be false.
EDIT: Thanks for the answers guys, I'm looking through them all. One answer I keep getting goes too general; I understand that ! is NOT, and I understand the concept of flipping the bool using it. However the implicit logical implications are what confuse me. In any given statement, I am used to thinking of !valid as a way of flipping the valid value; Not testing a condition. It's the syntax of using it to test a condition that tricks me. In other words, writing while(!valid) reads literally to me as while(NOTvalid), not while(valid==false). I can't get myself to understand why in this case, !valid reads as a condition and not just a bit-flip.
Loops (and ifs) are controled by an expression of type bool.
In while ( !valid ), the expression is !valid, the operator
not applied to the value of the variable valid.
while ( !valid ) means (literally) while the expression
!valid (which means "not valid") is true.
For the rest, the code you're copying is pretty bad. I wouldn't
use it as an example if I were you.
As for your own code:
_tmain is very particular to Microsoft. You don't want to
use it. If your writing a console application, just use main.
(Same thing holds for _TCHAR, rather than char.)
Neither _tmain nor main can return a float. The return
type of main should always be int. I'm less familiar with
_tmain, but it's either int or void. (Probably int, if
you're in a console mode program.)
!true is false. Always. (Programming is different than
the real world. There are no maybes.) Why be more
complicated than necessary?
There's no need for the flag variable at all. You
can just write:
cin >> operatorSelection;
while ( !cin || operatorSelection > 4 || operatorSelection < 1 ) {
// ...
}
In case of error, you currently only ignore a single
character. You probably want to ignore up to and including the
end of line.
(std::cin.ignore( std::numeric_limits<std::streamsize>::max() );.
And the condition in your if will always be true. (See my
version above.) Where do you expect to find a number which is
neither less than for nor greater than one?
In your code, inside the loop, just add:
else
validInput = true;
after the if closing bracket.
You want to get out of it once the user has typed a correct value.
You want to run the loop "while there is not a valid input". Remove the non-bold words, and translate to C++.
Of course, the second case is not working, because nothing changes validInput inside the loop, so it stays "invalid", and the loop continues forever (And if you want to set something to false then bool validInput = !true; is more convoluted than bool validInput = false; - the compiler will do the same thing, but someone reading the code will have to think to see what it does - it is a good thing to think when reading code, but it's not a good thing to write code that is more complicated than necessary...).
A while loop has a condition and a body, the body is executed as long as the condition evaluates to true.
From the C++ standard:
6.5.1 The while statement
In the while statement the substatement is executed repeatedly until the value of the condition (6.4) becomes
false. The test takes place before each execution of the substatement.
A while loop can have one of the following forms
while ( condition ) statement
while ( condition )
{
statement(s)
}
The ! operator is a logical not and this is how you should read it: while not valid. You could have also written that as:
while(valid == false)
or
while(valid != true)
Note that here, again, != is equivalent to not equal.
nijansen forgot to add the most elegant one
while(!valid)
which is the same as the 2 others