POV-Ray : Newsgroups : povray.off-topic : My first C++ program : Re: A test Server Time
1 Oct 2024 09:25:45 EDT (-0400)
  Re: A test  
From: Orchid XP v8
Date: 21 Sep 2008 04:15:09
Message: <48d6028d$1@news.povray.org>
>> module Main where
> 
>> import System.Random
> 
>> main = do
>>    target <- randomRIO (1, 100)
>>    guess target
> 
>> guess target = do
>>    putStr "Guess: "
>>    txt <- getLine
>>    let number = read txt :: Int
> 
>>    case compare number target of
>>      LT -> do putStrLn "Too low.";  guess target
>>      GT -> do putStrLn "Too high."; guess target
>>      EQ -> do putStrLn "You win!"
> 
>   Now you'll have to implement the same program in C++. ;)

This appears to work:



#include <iostream>
#include <sstream>
#include <cstdlib>
#include <ctime>

void guess(const int target)
{
   while (true)
   {
     std::cout << "Guess: ";
     std::string  txt;
     std::cin  >> txt;

     std::istringstream iss(txt);
     int number;
     iss >> number;

     if (number < target) {std::cout << "Too low."  << std::endl; continue;}
     if (number > target) {std::cout << "Too high." << std::endl; continue;}
     break;
   }

   std::cout << "You win!" << std::endl;
}

int main()
{
   std::srand(std::time(0));
   const int target = std::rand() % 99 + 1;
   guess(target);
}



A few missing semicolons, a few missing std:: qualifiers, and then it 
basically ran first time.

(It is unclear to me whether I could have thrown in a few more "const" 
keywords, but for such a short example it probably doesn't matter.)

-- 
http://blog.orphi.me.uk/
http://www.zazzle.com/MathematicalOrchid*


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.