{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

simpleio - if cin.fail exit if input was bad return r...

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 Document Right 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 << "What is your age? "; cin >> age; c cout << "You said: " << salary << " and " << age << 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 << "What is your salary? "; cin >> salary; cin.ignore(255,'\n'); // try removing this line cout << "What is your full name? "; //char myName[50]; / //cin.getline(myName,50); getline( cin, name ); cout << "hello, " << name << 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 << "Type 'abcdef': "; cin.ignore( 5, 'c' ); cin >> chararray; cout << chararray; } void simpleio() { Example1(); //Example2(); //Example3(); //Example4(); / //return 0; }...
View Full Document

{[ snackBarMessage ]}