mardi 3 novembre 2015

C++: Tracking iterations in code (after n iteration do x) / User input

I had a question in regards to a beginner assignment I was working on. The initial assignment requires me to make a program that asks the user to enter any number other than 5 until the user enters 5. If they enter 5 the program will alert them saying they input 5. The next part of the assignment requires me to make a condition where after 10 iterations or 10 inputs of a non 5 value, the program messages the user and exits the program. I finished the first part but had trouble with the second part. I searched stackoverflow and found something about the "get" function, but I'm not sure how to implement it correctly. How would I track the number of inputs or iterations and make a condition to where after n number of successful iterations the program exits?

Also , how would I make a condition to where if the user inputs a character instead of an integer the program warns the user and exits?

Thanks for the help. Here is the code I have written so far.

// This program works, however, if user inputs a character or a very large number
//then the program malfunctions.
// Learn more about the get function.
#include <iostream>
using namespace std;

int main()
{
    int inpt;

    cout << "Please input any number other than 5.\n";
    cin >> inpt;

    while (inpt != 5)
    {
        cout << "Please input another number other than 5.\n";
        cin >> inpt;
    }

    if (inpt = 5)
        {
            cout << "Hey! You weren't supposed to enter 5!";
        }


    return 0;
}

Aucun commentaire:

Enregistrer un commentaire