Home > Mobile >  C random number string from seed value
C random number string from seed value

Time:08-12

This might be ridiculously easy but I'm still beginner. I would need to create a string including 5 random numbers seperated by spaces.

With code below, I get e.g. random = "12345" but I need string random = "1 2 3 4 5" in the end of the code because later I need to use these numbers as a string in istringstream is { random } command.

So to sum up, I need to create string including 5 random numbers seperated by spaces.

Thanks for help in advance.

int main()
{
        cout <<"Enter seed value: ";
        int seed;
        cin >> seed;

    srand(seed); // random number generator uses seed value entered by the user

    for (int i = 1; i <= 5; i  ) { // print 25 numbers
        int random = 1   (rand() % 5); // numbers are between 1 - 5

        cout << random ;
    }
    return 1;
}

CodePudding user response:

Just as you need to string for an istringstream later you can use an ostringstream to create the string in the first place.

ostringstream oss;
for (int i = 0; i < 5;   i)
{
    if (i > 0)     // if not the first number add a space between the numbers
        oss << ' ';
    oss << 1   (rand() % 5); // add the random number
}
string randomString = oss.str(); // get the string out of the ostringstream

CodePudding user response:

You can print the space too after printing the random number, if printing is what you want

int last = 5;
for (int i = 1; i <= last; i  ) { // print 25 numbers
    int random = 1   (rand() % 5); // numbers are between 1 - 5
    cout << random ;
    if( i != last ) cout << " ";
}
  • Related