Can someone help me write this code to c++. I wanted to see how hard it was to self teach c++ from only knowing basic c.
*************
#include <stdio.h> /*included to allow for printf()/scanf() to be used*/
#include <time.h> /*included to allow time() to be used*/
#include <stdlib.h> /*include to allow rand() and srand() to be used*/
int main(void){
int x, user, guess; /* variable to hold our random integer*/
srand(time(NULL)); /*seeds random number generator. Do this just once*/
x = rand()%51;
printf("What number do you think I chose?: \n");
if(user>x){
printf("The number is lower than that\n");
}
else if(user<x){
printf("The number is higher than that\n");
}
else if(user==x){
printf("YOU GOT IT!\n");
break;
}
//#include <stdio.h> /*included to allow for printf()/scanf() to be used*/
//#include <time.h> /*included to allow time() to be used*/
//#include <stdlib.h> /*include to allow rand() and srand() to be used*/
#include <cstdio>
#include <ctime>
#include <cstdlib> // these are the equivalent C++ headers
// int main(void){
int main() { // preferred C++ style
// int x, user, guess; /* variable to hold our random integer*/
// in C++, we define variables close to their point of use.
// in particular, we do not define a variable till we know how to initialize it
// srand(time(NULL)); /*seeds random number generator. Do this just once*/
std::srand( std::time(nullptr) ) ; // or std::srand( std::time(0) ) ;
// standard library entities are in namespace std
// x = rand()%51;
enum { UPPER_BOUND = 51, MAX_GUESSES = 5 } ; // we try to avoid magic numbers
constint x = std::rand() % UPPER_BOUND ;
// printf("What number do you think I chose?: \n");
std::printf("What number do you think I chose?: \n");
// for(guess=0; guess<5; guess++){
for( int guess = 0 ; guess < MAX_GUESSES ; ++guess ) {
// we prefer using the prefix ++ over the postfix ++
// scanf("%d", &user);
int user ; std::scanf( "%d", &user ) ;
if( user>x ){
// printf("The number is lower than that\n");
std::printf("The number is lower than that\n");
}
elseif(user<x){
// printf("The number is higher than that\n");
std::printf("The number is higher than that\n");
}
//else if(user==x){
else { // user== x if both the earlier checks yielded false
// printf("YOU GOT IT!\n");
std::printf("YOU GOT IT!\n");
break;
}
}
// return 0 ;
// not required in C++; if there is no return statement, return 0 is assumed
}
#include <iostream>
#include <ctime>
#include <random>
int main()
{
enum { MIN_VALUE = 0, MAX_VALUE = 51, MAX_GUESSES = 5 } ;
std::mt19937 rng( std::time(nullptr) ) ;
std::uniform_int_distribution<> distr( MIN_VALUE, MAX_VALUE ) ;
constint x = distr(rng) ;
std::cout << "What number do you think I chose?: " ;
for( int guess = 0 ; guess < MAX_GUESSES ; ++guess )
{
int user ; std::cin >> user ;
if( user > x ) std::cout << "The number is lower than that\n" ;
elseif( user < x ) std::cout << "The number is higher than that\n" ;
else { std::cout << "YOU GOT IT!\n" ; break ; }
}
}