samedi 17 septembre 2016

setw or setfill is ending my program

I am relatively new to programming and have ran into a problem. This entire program works as expected until I add:

cout << setw(digitsIn) << setfill('0') << code << endl;

Once I add this, the program just returns to 0 upon running it. I went and rewrote the entire digitsInCode == 0 section with setw in it, in a separate program and it worked just fine. Therefore it leads to believe that something with loops is causing it to end rather than running the way it should. I am stuck and unable to figure how to fix this. I would appreciate any help and I think I given everything I need. If not, please ask, this is my first time posting on stackoverflow.

#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <stdlib.h>
#include <sstream>
#include <iomanip>
#include <time.h>
using namespace std;

int main() {
    int digitsInCode;
    int code;
    int digitsIn;

// Random Number Generator
// get a seed value for the pseudo-random number generator
srand (time_t(NULL));
cout << endl;



        //Only accepting input if equal to 3, 4 or 5
while((digitsInCode != 0) && (digitsInCode != 3) && (digitsInCode != 4) && (digitsInCode!= 5)) {
    cout << "Enter number of digits in code (0, 3, 4 or 5): "; // Repeat until user enters a correct number
    cin >> digitsInCode;

    // define constants for random values
    if (digitsInCode == 3) {
        const int randMax = 999;
        const int randMin = 100;
        int val = rand() % randMax + randMin;
        cout << "Number to guess: " << val << endl;;


        // define constants for random values
    } else if (digitsInCode == 4) {
        const int randMax = 9999;
        const int randMin = 1000;
        int val = rand() % randMax + randMin;
        cout << "Number to guess: " << val << endl;;


        // define constants for random values
    } else if (digitsInCode == 5) {
        const int randMax = 99999;
        const int randMin = 10000;
        int val = rand() % randMax + randMin;
        cout << "Number to guess: " << val << endl;;

    }

    else if (digitsInCode == 0) {
        cout << "Enter code: " << endl;
        cin >> code;
        cout << "Enter number of digits in code: ";
        cin >> digitsIn;
        cout << setw(digitsIn) << setfill('0') << code << endl;
        cout << "Number to guess: " << endl;
    }
    else {
        cout << "Try Again" << endl;
    }

}






// stringstream ss; // Converting digitsInCode to string
//  ss << digitsInCode << endl;
//  string newString = ss.str();






return 0;

}




Aucun commentaire:

Enregistrer un commentaire