Why won't this compile?

Code is pretty standard. I'm getting an error that the compiler doesn't recognize "printf" .... but isn't included in #include <cstdlib>?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 #include <iostream>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <time.h>

using namespace std;


void insertionSorting(int *array, const int& length);

int main(int argc, char** argv) {
    const int n=100;

    int *randomArray = new int [n];
    const unsigned long N=1000000;

    for(int i=0; i <n; i++){

        //comment the following line will generate a same array each time!

         //srand(time(NULL)+2*rand());
         randomArray[i] = rand() % N;
    }

   // for (int i=0;i<n;i++)
    //cout<<"randomArray["<<i<<"] = "<<randomArray[i]<<endl;

    clock_t t=clock();
    insertionSorting(randomArray, n);
    t=clock()-t;

    printf ("It took %d clicks, (%f seconds) to finish"
            " sorting this array with %d entries"
            " \n",(int) t,((float)t)/CLOCKS_PER_SEC, n);

    int print_bit=1; // 0: no printout

    if (print_bit){
        for (int i=0;i<n;i++)
                cout<<"randomArray["<<i<<"]= "<<randomArray[i]<<endl;
    }
closed account (o3hC5Di1)
Hi there,

printf() is defined in <cstdio>.
http://www.cplusplus.com/reference/cstdio/

Hope that helps.

All the best,
NwN
Use cout since you included <iostream>
include <cstdio> if you want to use printf()
Don't mix C++ input output with C input output. You must choose between only using cout and cin or only using printf and scanf - you should not mix them.
Last edited on
Ah, I feel like a dunce!

Thanks a lot for the help guys
We posted at the same time - you may have missed my post. It's important that you read it unless you want your program to randomly crash ;)
Last edited on
closed account (o3hC5Di1)
@L B - would you be so kind as to explain why? I'm just interested in the reason, no critique intended.

All the best,
NwN
> Don't mix C++ input output with C input output.
> unless you want your program to randomly crash ;)

It is perfectly safe to mix C++ input output with C input output on standard streams.
Unless an explicit std::ios_base::sync_with_stdio(false) was issued.
http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio

Urban legends never die, do they?
http://www.cplusplus.com/forum/general/110331/#msg602380
Last edited on
I stand corrected - apparently I didn't learn the first time either.
Topic archived. No new replies allowed.