simpleio - if( cin.fail() ) // exit if input was bad...

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

View Full Document Right Arrow Icon
// simpleio.cpp / // Show how to input and display a string / #include <iostream> #include <string> using namespace std; u void Example1() { string firstName; int age; double salary; d // values of age and salary are undetermined cout << age << ", " << salary << endl; c // try entering a blank string. C++ does not terminate // the input if you just press [Enter]: / /* cout << "What is your first name? "; cin >> firstName; */ cout << "How old are you? "; cin >> age; c // remove end-of-line char (and trailing spaces) from buffer cin.ignore(10,'\n'); c // Suggestion: put each stream element on a separate // line for easy editing: / cout << "Your name is " << firstName << ", and your age is " << age << endl; } void Example2() // iostreams accept invalid input without throwing // an exception; subsequent input, however, fails. { double salary; int age; i // try entering invalid characters at runtime: cout << "What is your salary? "; cin >> salary; cin.ignore(10,'\n'); // remove the \n from input buffer / // check for failed input stream
Background image of page 1

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

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

Unformatted text preview: if( cin.fail() ) // exit if input was bad return; r cout &lt;&lt; &quot;What is your age? &quot;; cin &gt;&gt; age; c cout &lt;&lt; &quot;You said: &quot; &lt;&lt; salary &lt;&lt; &quot; and &quot; &lt;&lt; age &lt;&lt; endl; } void Example3() // input combination of numeric and multi-word string // when entering the salary, add a bunch of spaces to the end { double salary; string name; cout &lt;&lt; &quot;What is your salary? &quot;; cin &gt;&gt; salary; cin.ignore(255,'\n'); // try removing this line cout &lt;&lt; &quot;What is your full name? &quot;; //char myName[50]; / //cin.getline(myName,50); getline( cin, name ); cout &lt;&lt; &quot;hello, &quot; &lt;&lt; name &lt;&lt; endl; } void Example4() // The ignore() method removes up to n characters // from the input stream, stopping when it finds // the delimiter character (default is eof). { char chararray[10]; cout &lt;&lt; &quot;Type 'abcdef': &quot;; cin.ignore( 5, 'c' ); cin &gt;&gt; chararray; cout &lt;&lt; chararray; } void simpleio() { Example1(); //Example2(); //Example3(); //Example4(); / //return 0; }...
View Full Document

This note was uploaded on 10/17/2010 for the course SCIS COP 4338 taught by Professor Kipirvine during the Spring '10 term at FIU.

Page1 / 2

simpleio - if( cin.fail() ) // exit if input was bad...

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

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