Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Can anyone help fix this?

Options
  • 04-10-2014 9:14pm
    #1
    Registered Users Posts: 529 ✭✭✭


    *FORGOT TO MENTION IN TITLE THAT THIS IS C++*

    I'm working on a small project at the moment which involves a random sum being generated, Its only addition at the moment but that would be easy to expand. It works fine, typing in the right answer tells you that you are correct while typing in the wrong answer tells you that you are incorrect and displays the correct answer but say you type in 'sdfldhfs' it tells you that that you are correct even though i have set it to say 'that is not a number'.
    I suspect i'm doing something fairly basic in the wrong way.
    If anyone could help me with this it would be great, its been annoying for the last few days!


Comments

  • Moderators, Computer Games Moderators, Technology & Internet Moderators Posts: 19,240 Mod ✭✭✭✭L.Jenkins


    I hate to do your work for you, but try this out.

    // Don't need as many libraries
    #include <string.h>
    #include <cstdlib>

    using namespace std;

    int main()
    {
    int a = 0, b = 0, sum = 0, x = 0;

    while(true) // Keeps going until you get a right answer
    {
    a = 1 + (rand() % 10);
    b = 1 + (rand() % 10);
    sum = a + b;

    cout << "Take a guess: \n";
    cin >> x; // Takes in a type int as x is defined as an int

    if(x != sum)
    {
    cout << "Wrong Answer!\n";
    }
    if(cin.fail()) // Checks if input for a valid type
    {
    cout << "Can not enter a string!\n";
    system("pause"); // If you want to keep going remove these to lines.
    break;
    }
    if(x == sum)
    {
    cout << "Correct\n";
    }
    }
    return 0;
    }

    The problem is with isalpha(num). It only checks for a character and it is a string you need to check for and cin.fail() does this. You can also change the while with a for loop. Remove the break from the code if you don't want the program to stop.


  • Registered Users Posts: 529 ✭✭✭Untamedlemon


    Thank you very much, that worked perfectly. Glad to have that problem sorted!
    Thanks.


  • Moderators, Computer Games Moderators, Technology & Internet Moderators Posts: 19,240 Mod ✭✭✭✭L.Jenkins


    The main issue is, do you understand it?


  • Registered Users Posts: 529 ✭✭✭Untamedlemon


    Yes I understand it now,
    Thank you for your help.


  • Moderators, Computer Games Moderators, Technology & Internet Moderators Posts: 19,240 Mod ✭✭✭✭L.Jenkins


    Good glad I could help.


  • Advertisement
Advertisement