This example was written by a group of students from my Winter 2000-2001
quarter section of CS-182. The function is an example of how string streams
can be used to verify that the correct type of data has been entered by
the user.
1// enterInt.h
2// Written by a group of students from section 1 of the Winter 2000-2001
3// offering of CS-182.
4// Date: 2-6-2001
5// This function will display "prompt" which should ask for an integer
6// and then allow the user to make an entry.
7// If the beginning of the entry is a valid integer value, the
8// function returns the value. If not, the function will repeat
9// displaying the prompt and accepting the user's entry until
10// a valid integer value is entered.
11int getInt(const string& prompt);
1// enterInt.cpp
2// Written by a group of students from section 1 of the Winter 2000-2001
3// offering of CS-182.
4// Date: 2-6-2001
5// This function will display "prompt" which should ask for an integer
6// and then allow the user to make an entry.
7// If the beginning of the entry is a valid integer value, the
8// function returns the value. If not, the function will repeat
9// displaying the prompt and accepting the user's entry until
10// a valid integer value is entered.
11
12#include <iostream>
13#include <string>
13.5#include <sstream>
14
15using std::cout;
16using std::endl;
17using std::getline;
18using std::string;
18.5using std::istringstream;
19
20int enterInt(const string& prompt)
21{
22 string input;
23 int retVal;
24 bool done = false;
25 do {
26 cout << prompt << endl;
27 getline(cin, input);
28 istringstream istr(input);
29 if(istr >> retVal) {
30 done = true;
31 }
32 } while(!done);
33 return retVal;
34}