Lec9 - Lecture 9: Getting Loopy PIC 10A Todd Wittman Sec...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 9: Getting Loopy PIC 10A Todd Wittman Sec 4.4 : Input Validation s So far we’ve assumed the user gives us proper input. But what if they don’t? Enter a number: four s When you do a cin statement, it actually returns a boolean: true if you were able to read the value correctly, false if it failed to read the specified type. s Returns the boolean true for a success, so we can use cin in an if statement. s Alternatively you could use the member function cin.fail( ) described in Sec 4.4.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 Example: Input Validation int main ( ) { int x; cout << “Enter a number: “; if ( cin >> x ) { cout << “Your number is “ << x << “.\n”; return 0; } else { cout << “Supposed to be a number.”; return 1; } } This will end the program. Use the return command with caution. This line does 2 things: 1.) Gets input x from user. 2.) Checks if read successful. Sec 4.5 : The while loop s Sometimes it’s useful to repeat a block of code, like HW 3. s We call a block of code that is repeated a loop . s Each repetition of the code is called an iteration . s The while loop acts like a repeating if statement, repeating the code below it as long as the boolean statement is true. Also called a stopping condition . while ( statement is true ) { ** STATEMENTS ** } s The braces { } enclose the code to repeat. s Like with if , indenting makes it easier to read.
Background image of page 2
3 Example of a while loop int x = -1; while ( x <= 0 ) { cout << “Enter a postive number: “; cin >> x; } cout << “Your number is “ << x << “.\n”; s What does this code do?
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 11/19/2011 for the course PIC 10A taught by Professor Wittman during the Fall '08 term at UCLA.

Page1 / 9

Lec9 - Lecture 9: Getting Loopy PIC 10A Todd Wittman Sec...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online