(Dreaded) Quiz 2 Next Monday
Strings Revisited string Is a Type in C++ Library <string> May Initialize or Assign with Double Quoted Values May Compare using Equality Operators Can Access Single Characters using Square Bracket Operator ([ ]) Can Use length() Object Function Can Add to String
#include <iostream> #include <string> using namespace std; int main() { string lastname, firstname; cout << "Enter last name: "; cin >> lastname; cout << "Enter first name: "; cin >> firstname; cout << "Your name is " << firstname << " " << lastname << endl; return(0); }
#include <iostream> #include <string> using namespace std; int main() { string lastname, firstname; bool instructor; cout << "Enter last name: "; cin >> lastname; cout << "Enter Firstname: "; cin >> firstname; if (lastname == "hanrath") instructor = true; else instructor = false; return(0); }
#include <iostream> #include <string> using namespace std; int main() { string word = "start"; cout << word << endl; word[0] = 'h'; word[1] = 'e'; return(0); }
#include <iostream> #include <string> using namespace std; int main() { string word = "start"; cout << word << endl; word[0] = 'h'; word[1] = 'e'; cout << "String length is: " << word.length() << endl; return(0); }
#include <iostream> #include <string> using namespace std; int main() { string word = "start"; cout << word << endl; word[0] = 'h'; word[1] = 'e'; cout << "String length is: " << word.length() << endl; word = word + " " + "healthy" + " " + word; return(0); }
More on Input Input Failure Common *MUST* Be Part of Test Plan cin Used for Input If User Enters Bad Type of Data, cin Left in failed state Must Use cin.clear() function to Start Over Must Use cin.ignore() function to Get Beyond Bad Input May Use cin as Condition in if Statement Pages 111-113, 175 in Malik
Input Failure Example #include <iostream> #include <string> using namespace std; int main() { int numEmployees; bool done = false; string garbage; while (!done) cout << "Enter number of employees: "; cin >> numEmployees; if (!cin) //if input stream in failed state cout << "Bad input, try again." << endl; cin.clear(); // changes input state to ok cin.ignore(200,'\n'); // gets beyond bad input characters } else done = true; return(0);
Know for Quiz 2 Everything through Exam 1 while, for, and do-while Loops New string Features Input Failure