Why is this infinite while loop with the printf not looping for ever?

Why is this ifinite while loop not repeating the printf statement? It only runs it once! please help me fix

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
  #include <ctime>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

int main()
{
char str[80];	

srand (static_cast <unsigned> (time(0)));
	
float r = static_cast <float> (rand() / static_cast <float> (RAND_MAX));

while(1)
	{
	printf("This is the random number: %f\n",rand);
	if (scanf("%c ",str) == EOF)
	{
	break;
	}
	
}
} 

Compile with warnings on.
main.cpp:17:16: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int (*)()' [-Wformat=]
         printf("This is the random number: %f\n",rand);
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~
main.cpp:13:11: warning: unused variable 'r' [-Wunused-variable]
     float r = static_cast <float> (rand() / static_cast <float> (RAND_MAX));
           ^


rand is a function, but you're passing it as a pointer instead of calling it.
r is the random number that you calculate once on line 13 and never use.

It only runs it once!
It's an infinite loop for me. scanf waits for user input. And look up what the return value of scanf means, because it doesn't mean what you think it means.
Last edited on
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
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

int main()
{
    char str[80];
    
    srand (static_cast <unsigned> (time(0)));
    
    float r = static_cast <float> (rand() / static_cast <float> (RAND_MAX));
    
    while(1)
    {
        printf("This is the random number: %f\n",rand);
        if (scanf("%c ",str) == EOF)
        {
            break;
        }
        
        std::cout << "Here we are \n"; // <---
        
    }
}


I havent checked it all the way to infinity but with the added line and checking out what scanf does you'll see you can get there with a few key inputs.


Great minds think alike.
Registered users can post here. Sign in or register to post.