want to add an error message if cin is not a number

#include <iostream>
#include <stdlib.h> //used for random numbers
#include <time.h>
#include <string>

using namespace std;
int main() {
int bridgeWidth ; //set bridge width to any number
int startPosition(0) ; // set starting posotion to the middle of the bridge
int currentPosition;
int stepCounter = 0;
int randomNumber; // random number -1, 0, 1
char yesKey;

srand( (unsigned)time( NULL ) ); // seed generator

cout <<" Please enter your desired bridge width: "<< endl;
cin >> bridgeWidth;


startPosition = (bridgeWidth/2)+1;

currentPosition = startPosition;
do { //move walker left or right
randomNumber = rand() % 3 -1; //rand: 0-32k, mod 3 gives 0,1,2
currentPosition = currentPosition + randomNumber;
stepCounter++;
//
// create the bridge section
//
cout << " |";
for ( int i = 2; i < bridgeWidth ; i++ ){
if ( i == currentPosition )
cout << "X"; //indicate walker position
else
cout << " ";
}
cout << "| " << stepCounter << endl;
//
// test if the walker stepped off of the bridge
//
if ( currentPosition <= 1 || currentPosition >= bridgeWidth ) {
cout << "Over the rail after " << stepCounter << "steps." << endl;
cout << "Hit y and then enter to do it again or any key to stop..." << endl;
cin >> yesKey;
if ( yesKey != 'y' )
return( 0 );
currentPosition = startPosition; //reet to start again
stepCounter = 0;
}
} while (1);
return( 0 );
}
Last edited on
stringstream will help you, unless you aren't allowed to use it.

header: sstream
object: stringstream

http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream

good luck
Or for an example of a more generic approach:
http://www.cplusplus.com/forum/beginner/108849/#msg592118
Topic archived. No new replies allowed.