-1

I am completely new in C and try to fill a vector with random integers and output it afterwards. However, it seems that the vector is always filled with the same number. What do I need to change to really get random payments? There is no limit, the number should only be within the value range of long. Here's my code:

    #include "stdafx.h"
    #include <stdlib.h>
    #include <stdio.h>
    #include <vector>
    #include <time.h>

int main()
{
    long x = 20;
    long y = 12;
    std::vector<long> entries;

    //initialize simple random number generator using current time
    srand(time(NULL));

    for (int step = 0; step < x; step++) {      
        entries.push_back(rand());
        ++entries[step];
    }

    for (std::vector<long>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
        printf("%ld\n", i);
    }       

    return 0;
}

EDIT: I want to solve the issue using plain C not c++!

  • **WARNING**: Using [`rand()` is considered harmful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) and you’re strongly encouraged to use an appropriate [random number generator facility in the Standard Library](http://en.cppreference.com/w/cpp/numeric/random) that produces actually random values. Your use of `time(NULL)` as a random number seed means that this will produce identical results if run in the same second, and on many platforms `rand()` is [*barely* random at all](http://dilbert.com/strip/2001-10-25). – tadman Jun 13 '18 at 15:35
  • 5
    You're getting the same number because you print the iterator and not the value referenced by it. That being said, since your code is C++, it would be best to use actual C++ idioms, e.g. stdout instead of printf and [random](http://en.cppreference.com/w/cpp/numeric/random) instead of C's `rand()`. As to the edit: if you want to use “plain C”, I do not see why you use vectors and iterators at all, C doesn't have them. – Norrius Jun 13 '18 at 15:37
  • 2
    "Plain C" because why? You have 99% functional C++ code here. – tadman Jun 13 '18 at 15:37
  • If you want plain C, you'll need to remove all the vectors. Is that what you want? – MartinVeronneau Jun 13 '18 at 15:39
  • @tadman *C++ is a superset of C, it's true* No, that's not true. Not at all. – Andrew Henle Jun 13 '18 at 15:39
  • I don't know how you expect a C solution when this is very much C++ code. – Christian Gibbons Jun 13 '18 at 15:40
  • @tadman could you please provice me a small example or code snippet how to use one of those random number generators? – MegaCleptomaniac Jun 13 '18 at 15:45
  • @tadman *I'm not going to get super pedantic here.* I'm not sure what you mean by that, but claiming C++ is a superset of C doesn't require much pedantic precision to sow confusion [given the significant differences between the two languages that prevent C++ from being a superset of C.](https://stackoverflow.com/questions/1201593/where-is-c-not-a-subset-of-c) – Andrew Henle Jun 13 '18 at 15:45
  • 1
    @AndrewHenle I'm retracting my comments because apparently you do want to get super pedantic. – tadman Jun 13 '18 at 15:47
  • 1
    I'm voting to close this question as off-topic because this is such a weird question. At present it boils down to "please fix my random number generator, and convert this C++ code to C". On the latter point it's too broad. – Bathsheba Jun 13 '18 at 16:21

2 Answers2

1

The main problem in your code is in your last loop

for (std::vector<long>::const_iterator i = entries.begin(); i != entries.end(); ++i) {
    printf("%ld\n", i);
}  

You're not printing a value from the vector, but an iterator that's pointing to it

Change the line inside the loop to printf("%ld\n", *i); to fix it.

Better yet, you can use a range-loop to make it even simplier

for(auto& number : entries){
std::cout<<number<<'\n'; //or printf("%ld\n",number), like in your code
}
Kaldrr
  • 2,780
  • 8
  • 11
1

If you want your solution to be pure C, you'll need to use arrays instead of vectors.

I'm missing some informations here, but a basic C program that uses srand() and rand() would look like this :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

#define NB_ENTRIES (20)
#define RANDOM_MAX_RANGE (50) // you should update that

// Don't use srand(time(NULL)) because if you start many time this
// program too quickly, you'll have the same values in all instances.
void Randomize(void)
{
  struct timeval time; 
  gettimeofday(&time,NULL);
  srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
}

// Returns a value between 0 and toNumber-1
// Thanks to Bathsheba for pointing out an error with my first version.
int RandomInt(int toNumber)
{
  return (int)(rand()/(RAND_MAX + 1.0) * toNumber);
}

// This better but slower version of RandomInt() will ensure
// an even distribution of random values if toNumber is
// greater than around three quarter of RAND_MAX
// NOTE : toNumber must be between 0 and RAND_MAX.
int BetterRandomInt(int toNumber)
{
  const int randomSize = RAND_MAX / toNumber;
  int returnValue;
  do 
  {
    returnValue = rand() / randomSize;
  }
  while (returnValue >= toNumber);

  return returnValue;
}

int main(void)
{
  int entries[NB_ENTRIES];
  int step;

  Randomize();

  for (step = 0; step < NB_ENTRIES; step++)
  {
    entries[step] = RandomInt(RANDOM_MAX_RANGE);
    // entries[step] = BetterRandomInt(RANDOM_MAX_RANGE);
  }

  for (step = 0; step < NB_ENTRIES; step++)
  {
    printf("%d\n", entries[step]);
  }       

  return 0;
}

Note that I'm using a fixed number of entries. You can make your array dynamic by using pointers and malloc(). Just comment if you need that, but I felt it was out of scope of the question.

MartinVeronneau
  • 1,296
  • 7
  • 24