Lec9 - 1 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

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

View Full DocumentRight Arrow Icon

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

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

Unformatted text preview: 1 Lecture 9: Getting Loopy PIC 10A Todd Wittman Sec 3.10 : Input Validation s So far weve assumed the user gives us proper input. But what if they dont? 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. 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 3.6 : The while loop s Sometimes its 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. 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;cout << Your number is << x << ....
View Full Document

Page1 / 9

Lec9 - 1 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