Hello guys i want to know how i can get the words in C++ like (a,b,c,d,f.....) im making dice game and when player will put word instead of number to tell him "You need to enter number!"

#include <iostream>
#include <ctime> 

using namespace std; 

int main()
{
    int dice;
    int money=10;
    int num;
    int answer;
    char roll;
    {
         cout<<"Your bank is $" << money << endl;
         cout<<"Please enter your guess for the next roll. It only costs $1.00 to play, If you are correct I will pay you $100.00:" <<endl;
         cin>>num;
         cin.get(roll);
         srand(time(NULL));
         dice = (rand()%6)+1;
         if(num > 6)
         {
                system("cls");
                cout << "You can't enter hieger number of 6!" << endl;
                cout << "Try again !" << endl;
                system("PAUSE");
         }
         if (num == dice)
         {
                      cout<<"Winner! The dice rolled " << dice <<endl;
                      money += 100;
                      cout << "Your bank acc is now $" << money << endl;
                      system("PAUSE");
         }
         else if (num != dice)
         {
                      cout << "Sorry the dice rolled " << dice <<endl;
                      money -= 1;
                      cout << "Your bank acc is now $" << money << endl;
                      system("PAUSE");
         }
    }
return 0;
}

Recommended Answers

All 14 Replies

and i also want to know how can program continue after choosing the number.
Ex:
Please enter your guess for the next roll. It only costs $1.00 to play, If you are correct I will pay you $100.00:

  • 5
  • Winner! The dice rolled 5
  • Your bank acc is now $110

-- Do you want continue ? y/n

Please enter your guess for the next roll. It only costs $1.00 to play, If you are correct I will pay you $100.00:

  • 3
  • Sorry the dice rolled 1
  • Your bank acc is now $109

Thanks :)

Here, this function will check if a string is a number or not:

bool isNumber(string str){
    bool doted=false;
    if (((int)str[0]<(int)'0' || (int)str[0]>(int) '9') && str[0]!='-') return false;
    for (size_t i=1;i<str.size();i++){
        if (!doted && str[i]=='.') doted=true;
        else if (((int)str[i]<(int)'0' || (int)str[i]>(int) '9')) return false;
    }
    return true;
}

and i also want to know how can program continue after choosing the number.

Well you could put it into an infinite for loop, which will be done untill the user enters 'n'...

string answer;
for (;;){
    cout<<"Insert number: ");
    cin>>answer;
    if (isNumber(answer)){
        //do your program
    }
    cout<<"Would you like to keep playing?";
    cin>>answer;
    if (answer=="n" || answer=="N" || answer=="No") break;
}

You could use the fail/badbit state flags to see if there was an error. So something like this:

#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int  number = 0;
    bool error  = false;

    do
    {
        cout << "[?] Enter a number: ";
        cin >> number;

        error = !cin;

        // Failbit or badbit is set.
        if (error)
            cout << "[!] Please enter a number.\n";

        // Note: The code clears the state flag and input buffer regardless. Depends a bit on what you think is
        // acceptable input. Something like "2323 12383" or even "123 hello" is accepted now, the remainder is just ignored.
        // It also treats numbers that are too big to fit into an int as erroneous input. It will also accept things like hexadecimal input.

        // Clear state flags.
        cin.clear();

        // Empty the input buffer.
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    while (error);

    return 0;
}

guys i realy can't figure out where to place this code in the game please can u help do that for me :S

Please anyone help ?? :/

If you can't place the supplied code into the one you posted at the start I'm starting to doubt if you've written it yourself. What is unclear about he code(s) provided and what prevents you from changing your own to follow them?

ok look wha i done but when i need to tupe numebr to roll the dice i need to put 2 numbers to start the rollng please some one help me

#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <winable.h>
#include <limits>
#include <ctime>

using namespace std;

int money = 10,num,dice;

string ans;

    int Answers()
    {
        if(ans == "13")
        {
               cout << "You are filled in your bank account $50" << endl;
               money += 50;
        }
        if(ans != "13")
        {
               cout << "[!] Wrong" << endl;
               system("pause");               
        }
    }
    int Questions()
    {
        cout << "If you answer true u will filled in bank $50" << endl;
        cout << "How much is 7 + 6 ?" << endl;
        getline(cin, ans);
        Answers();
    }

int main(int)
{   
    char roll;
    {
         while (true)
         {
               cout<< "Money in bank: $" << money << endl;
               cout<< "Please enter your guess for the next roll. It only costs $1.00 to play, If you are correct I will pay you $100" <<endl;
               cin >> num;
               cin.get(roll);
               srand(time(NULL));
               dice = (rand()%6)+1;
               string some_number;
               getline(cin, some_number);
               if (cin.fail() == true)
               {
                      cout << "[!] Please enter a number." << endl;
                      system("pause");
                      return false;
               }
               if(num > 6 || num < 1)
               {
                      system("cls");
                      cout << "Your number " << num << endl;
                      cout << "[!] You can't enter hieger number of 6 or lower than 1" << endl;
                      cout << "Try again !" << endl;
                      system("PAUSE");
                      return false;
               }
               if(money <= 0)
               {
                      cout << "You dont have money!" << endl;
                      cout << "You can enter moeny in bank if you answer on some questons." << endl;
                      Questions();
               }
               if (num == dice)
               {
                      cout << "Rolling the dices..." << endl;
                      Sleep(2500);
                      system("cls");
                      cout << "Your number " << num << endl;
                      cout << "Winner! The dice rolled " << dice <<endl;
                      money += 100;
                      cout << "Your bank account is now $" << money << endl;
                      cout << "\n";
               }
               else if (num != dice)
               {     
                      cout << "Rolling the dices..." << endl;
                      Sleep(2500);
                      system("cls");
                      cout << "Your number " << num << endl;
                      cout << "Sorry the dice rolled " << dice <<endl;
                      money -= 1;
                      cout << "Your bank account is now $" << money << endl;
                      cout << "\n";
               }
         }
    }
return 0;
}

You would find it a lot easier if you factor the code into small functions, each function doing just one thing, and doing it well.

Problem one: get validated numeric input from user

int int_in_range_from_stdin( int min, int max )
{
    int number ;
    std::cout << "enter an integer in the range [ " << min << ", " << max << " ]: " ;

    if( std::cin >> number && number >= min && number <= max ) return number ;

    std::cout << "error in imput.\n" ;
    std::cin.clear() ; // clear ia possible error state
    std::cin.ignore( 1000, '\n' ) ; // and throw away cruft in the input buffer
    return int_in_range_from_stdin( min, max ) ;
}

.
.
Problem two: roll the dice multiple times

int generate_random_roll()
{
    static const int init_once = ( std::srand( std::time(nullptr) ), 0 ) ;
    int roll ;
    while( ( roll = int( ( std::rand() / ( RAND_MAX + 1.0 ) ) * 6 ) + 1 ) == 7 ) ;
    return roll ;
}

.
.
etc...

@vijayan121:
Any specific reason why you chose to recurse on Problem 1 - Line 11? If the user enters a wrong input 5 times, then that function will return 6 times. I would suggest a do while to avoid that.

Any specific reason why you chose to recurse on Problem 1 - Line 11?

I thought the 'if the attempt to read a valid number fails, clean up and try again' logic bacomes more obvious with recursion.

.
.

If the user enters a wrong input 5 times, then that function will return 6 times. I would suggest a do while to avoid that.

Performance is irrelevant in this situation; in the time it takes the user to enter one number, a million instructions can be executed.

But just for the sake of argument, let us say that performance is absolutely critical.
The last line in the function is: return int_in_range_from_stdin( min, max ) ;
This is classic tail call recursion, and every mainstream compiler knows how to perform TCO.

For example, with gcc, the tail recursive version of a function typically produces slightly tighter code than the iterative version. For instance, 13 instructions vs. 15 for:

// invariant: cstr is a string of decimal literals
int recursive_decimal_string_to_number( const char* cstr, int n = 0 )
{
    if( cstr[0] == 0 ) return n ;
    return recursive_decimal_string_to_number( cstr+1, n*10 + cstr[0] - '0' ) ;

    /* g++ 4.8 -O3
    __Z34recursive_decimal_string_to_numberPKci:
        movl    4(%esp), %ecx
        movl    8(%esp), %eax
        movsbl  (%ecx), %edx
        testb   %dl, %dl
        je  L2
    L6:
        addl    $1, %ecx
        leal    (%eax,%eax,4), %eax
        leal    -48(%edx,%eax,2), %eax
        movsbl  (%ecx), %edx
        testb   %dl, %dl
        jne L6
    L2:
        rep
        ret
    */
}

// invariant: cstr is a string of decimal literals
int iterative_decimal_string_to_number( const char* cstr )
{
    int n = 0 ;
    for( int i = 0 ; cstr[i] != 0 ; ++i ) n = n * 10 + cstr[i] - '0' ;
    return n ;

    /* g++ 4.8 -O3
    __Z34iterative_decimal_string_to_numberPKc:
    LFB1:
        movl    4(%esp), %ecx
        movsbl  (%ecx), %edx
        testb   %dl, %dl
        je  L13
        addl    $1, %ecx
        xorl    %eax, %eax
    L12:
        addl    $1, %ecx
        leal    (%eax,%eax,4), %eax
        leal    -48(%edx,%eax,2), %eax
        movsbl  -1(%ecx), %edx
        testb   %dl, %dl
        jne L12
        rep
        ret
    L13:
        xorl    %eax, %eax
        ret
    */
}
commented: Thanks for clearing up :-) +13

lol what is this ??? :S

lol what is this ???

It is the mnemonic form of the low level code generated by the compiler.
Don't bother about it right now.

What you need to understand is fairly simple:

  • Performance is a design constraint, not a design goal.
  • Programmer time is more expensive than machine time.
  • People who write compilers are experts at low level optimizations; a typical application programmer is not.

So concentrate on the high-level data structures and algorithms; write the simplest, most transparent kind of code that you can; do your part well, and let the compiler do its part well.

If you want to multiply an unsigned int value by 8, write:
value *= 8 ; and not value <<= 3 ;
You may know that strength reduction is possible, that a shift is faster than a multiply on this particular platform; the writer of the compiler will know at least as much as you do.

realy nice writed but i have 3 questions
1) What is compiler
2) How can be used and what is algorithm
3) For what is that code you write for what can be used ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.