Skip to content

Instantly share code, notes, and snippets.

@paranoiacblack
Created October 29, 2012 06:45
Show Gist options
  • Save paranoiacblack/3971976 to your computer and use it in GitHub Desktop.
Save paranoiacblack/3971976 to your computer and use it in GitHub Desktop.
CS 10 SI Classroom Session 5 - Removing duplicated code into a function
#include <iostream>
using namespace std;
int main() {
string twoCharInput = "";
string fiveCharInput = "";
string tenCharInput = "";
// Make user continue entering word until it is the
// correct size.
do {
cout << "Type in a 2 character word: ";
cin >> twoCharInput;
} while (twoCharInput.size() != 2);
do {
cout << "\nType in a 5 character word: ";
cin >> fiveCharInput;
} while (fiveCharInput.size() != 5);
do {
cout << "\nType in a 10 character word: ";
cin >> tenCharInput;
} whlie (tenCharInput.size() != 10);
cout << "\nThe two character word is " << twoCharInput << endl
<< "The five character word is " << fiveCharInput << endl
<< "The ten character word is " << tenCharInput << endl;
return 0;
}
#include <iostream>
using namespace std;
// Returns a string with @size amount of characters
// received from the user.
string getInputWithSize(int size) {
string temporaryString = "";
do {
cout << "\nType in a " << size << "character word: ";
cin >> temporaryString;
} while (temporaryString.size() != size);
return temporaryString;
}
int main() {
// Phew, much less code. Also, no typos or ugly copy-pasting.
string twoCharInput = getInputWithSize(2);
string fiveCharInput = getInputWithSize(5);
string tenCharInput = getInputWithSize(10);
cout << "\nThe two character word is " << twoCharInput << endl
<< "The five character word is " << fiveCharInput << endl
<< "The ten character word is " << tenCharInput << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment