0

Can you help me guys? I'm a total beginner. My code worked fine then KEEP LOOPING FOREVER and never goes back to or cmd would crash with "Process terminated with status -1073741676". It should loop once then CIN >> again. It happens when I enter 10 digit numbers in my CIN >>.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

class noteAssign {      //This class return "A" if the random number generated is between 1 and 10
    public:
        int x;
        int noteOut(int x){
            if(x>1 && x<10){
                cout << "ITS A" << endl;
                return x;
            }else{
            cout << "IT'S NOT A" << endl;
            return x;
            }
            }
}gonote;

int main()
{
    cout << "Match the note's Hertz!" << endl;
    cout << "Your answer may range from 1 to 20" << endl;
    cout << "Type 0 to quit" << endl;

    int noteIn;                 //No real purpose YET

    do {
        srand(time(0));             //ADDING MULTIPLE RAMDOMIZER FOR WIDER RANDOM RANGE
        int rand1 = 1+(rand()%20); //randomizer 1
        int rand2 = 1*(rand()%20); //randomizer 2
        int hzout = (rand1 * rand2 + rand1 / rand2)%20; //rand 3
        noteAssign gonote;
        cout << gonote.noteOut(hzout) << endl;      //calls the function and gives the parameter
        cin >> noteIn;          //No real purpose YET
    } while(noteIn != 0);       //program quits when you enter "0"

};
Ry-
  • 218,210
  • 55
  • 464
  • 476
Shu Pesmerga
  • 155
  • 1
  • 1
  • 15
  • 7
    A 10 digit number is too big for your `int`. This results in the formatted extraction operator failing, setting the input stream to an error state. And because you never clear the input stream's error state, you just keep looping forever. – Sam Varshavchik May 12 '18 at 03:01
  • To fix it (assuming you won't type in 20+ digits), try `#include ` then use the type `int64_t` for `noteIn`. Still, if they type 'x' or something that still can't be parsed into a valid value for `noteIn`, it will "spin". You could use `if (!(cin >> noteIn)) { std::cerr << "bad input\n"; exit(1); }`, or a `while` loop wherein you re-prompt for input, `cin.clear()` and `ignore` the rest of the line - see [here](https://stackoverflow.com/q/5131647/410767)). – Tony Delroy May 12 '18 at 03:14
  • 1
    Alternatively, if you're never actually *using* it as an integer, you could take the input as a string directly. – o11c May 12 '18 at 04:02

0 Answers0