Hi,

I recently bought a book-The Complete Reference C++ by Herbert Schildt. The first part explains about the similarities about C++ and C. The syntax used is different from the one my lecturer is teaching.
eg:
cout<< is replaced by printf
cin>> is replaced by scanf

I would like to know which syntax is more preferred in the programming world for C++.

Another topic I would like to ask is, C++ have a function:
rand()

I did read it on the tutorial but the number that is generated is the same-41. What did I do wrong here? part of the code is something as follow:

magic = rand()
cout<<magic;

Oh and what's the difference between <iostream> and <stdio>?
Thank you.

Edited 6 Years Ago by wilsonz91: n/a

Use cout and cin instead of the C function printf and scanf, after all this
is C++.

Using rand, you have the correct idea, but you also have to seed it.
Insert this code : srand( time(0) ) at the very beginning of your main.
That code seeds the rand function so that it spits out seemingly random
numbers. You will have to import ctime header file to use time(0);

Using rand, you have the correct idea, but you also have to seed it.
Insert this code : srand( time(0) ) at the very beginning of your main.
That code seeds the rand function so that it spits out seemingly random
numbers. You will have to import ctime header file to use time(0);

#include<iostream>
using namespace std;

int main()
srand( time(0) )
{
	int x;
	
	x = rand();
	cout<<x;

	return 0;
}

Did you meant something like this?it produces error, so i must have got it wrong somewhere. By the way, what's the meaning of 'seed'?

Edited 6 Years Ago by wilsonz91: n/a

Place it inside of main()

int main()
{
   srand( time(0) );

A seed is a starting point in the internal sequence for a pseudo-random number generator. Giving the same seed twice would result in the same sequence of numbers.

For more info, check out the tutorial on Narue's website. It's infinitely more comprehensive than anything I could come up with off the top of my head here.

Edited 6 Years Ago by jonsca: n/a

I'm not sure who the founder is but she's associated with it (and written the tutorials) for sure. I was being informal.

Place it inside of main()

int main()
{
   srand( time(0) );

It comes out the error 'time' undeclared identifier. By the way, i'm using visual c++ 6.0

You need to #include <ctime> (it might have to go in as #include <time.h> because VC++ 6 uses some of the old headers). Forgot that in the other post.

Edited 6 Years Ago by jonsca: n/a

This question has already been answered. Start a new discussion instead.