locked
New book trying to work through RRS feed

  • Question

  • I recently bought "C++ Without Fear by Brian Overland". I just worked through a program example called NIM. It worked correctly. Another example he wanted us to work on was only allowing a positive integer to be used for the starting total. I entered the snippet of code from the example downloads I have but whenever I run it and enter the starting total as -1 it will still work. It is supposed to say "Please enter a positive integer only". Here is the code for the entire program. Can someone tell me what I did incorrectly? I am still VERY new to C++ but I want to learn it to change my life. Someone please look over my code and help me. Thanks.

    Randy

    #include

    <iostream>

    using

     

     

    namespace std;

    int

     

     

    main() {

     

     

    int total, n;

    cout <<

     

    "Welcome to NIM. Pick a starting total: ";

    cin >> total;

     

     

     

    while (total < 1) {

    cout <<

     

    "Please pick positive integer only.";

    cout <<

     

    "Pick starting total: ";

    cin >> total;

     

    }

     

     

     

    while (true) {

     

     

    // Pick best response and print results

     

     

    if ((total % 3) == 2) {

    total = total -2;

     

    cout <<

     

    "I am subtracting 2." << endl;

    }

     

    else {

    total--;

     

    cout <<

     

    "I am subtracting 1." << endl;

    }

     

    cout <<

     

    "New total is " << total << endl;

     

     

    if (total == 0) {

    cout <<

     

    "I win!" << endl;

     

     

    break;

    }

     

     

     

    // Get users response; must be 1 or 2

    cout <<

     

    "Enter number to subtract (1 or 2): ";

    cin >> n;

     

     

     

    while (n < 1 || n > 2) {

    cout <<

     

    "Input must be 1 or 2." << endl;

    cout <<

     

    "Re-enter: ";

    cin >> n;

     

    }

     

    total = total -n;

     

    cout <<

     

    "New total is " << total << endl;

     

     

    if (total == 0) {

    cout <<

     

    "You win!" << endl;

     

     

    break;

    }

     

    }

     

    system(

     

    "PAUSE");

     

     

    return 0;

    }

     

     

     

    Monday, December 26, 2011 8:46 PM

All replies

  • I experienced the same. I uninstalled and reinstalled lasted version of dotnetfx.exe but continue to get same error. Sent request to help desk and hope to hear back soon.
    fengpig
    • Edited by bfdr sggjhy Wednesday, December 28, 2011 6:01 AM
    Wednesday, December 28, 2011 6:00 AM