c++ - Program returning multiple results -
i'm writing basic random number guessing game, , i'm trying perfect bit when comes entering illegal characters, , long numbers outside of range 1-100 entered program tells user , user gets redo it, same goes letters. however, if enter 23x5 end getting double error messages, both letter , high/too low depending on random number. how sort out entry go under letter error message well?
here's code: header.h
#ifndef header_h #define header_h int nguessednumber; int nnumberofguesses = 1; int nrandomnumber; int userinput(); #endif
source.cpp
#include "stdafx.h" #include <iostream> #include <cstdlib> #include <ctime> using namespace std; extern int nguessednumber; int userinput() { while(!(cin >> nguessednumber)) { cin.clear(); while(cin.get() != '\n'){} cout << "i asked number between 1 , 100.\n"; } return nguessednumber; }
main.cpp
#include "stdafx.h" #include <iostream> #include <cstdlib> #include <ctime> #include "header.h" using namespace std; int main() { srand(time(0)); nrandomnumber = rand() % 100 + 1;// sets random number between 1 , 100 cout << "guess number 1 100: " << endl; userinput(); while (nguessednumber != nrandomnumber) { if ((nguessednumber < 1) || (nguessednumber > 100)) { cout << "oi! between 1 , 100!\n"; userinput(); } else { if (nguessednumber < nrandomnumber) { (nguessednumber; nguessednumber < nrandomnumber; nnumberofguesses++) { cout << "too low, try again!" <<endl; userinput(); } } else if (nguessednumber > nrandomnumber) { (nguessednumber; nguessednumber > nrandomnumber; nnumberofguesses++) { cout << "too high, try again!"<< endl; userinput(); } } } } if (nguessednumber == nrandomnumber) { cout << "congratulations! " << nguessednumber << " correct!" << endl; cout << "you guessed " << nnumberofguesses << " times." << endl; } system("pause"); return 0; }
read whole lines std::cin
, parse them individually using std::istringstream
:
int userinput() { std::string line; while (getline(std::cin, line)) { std::istringstream is(line); if (is >> nguessednumber) { ... return nguessednumber; } else { ... } } }
Comments
Post a Comment