top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Return value as string from a c++ function?

+1 vote
324 views

I have a string array that contains 20 words. I made a function that take 1 random word from the array. But I want to know how can I return that word from array. Right now I am using void function, I had used char type but it wont work.
Please help here? Need to make word guessing game.

#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>
#include <string>
using namespace std;

void random(string names[]);

int main() {
     char a;
     string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
                       "kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
                       "saule", "parks", "svece", "diegs", "migla", "virve"};

    random(names);

    cout<<"VARDU MINESANAS SPELE"<<endl;
    cin>>a;

    return 0;
}

void random(string names[]){
    int randNum;
    for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
       srand( time(NULL) ); /// seed for the random number generator.
       randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
       names[i] = names[randNum];
    }

    //for (int i = 0; i < 1; i++) {
      //cout << names[i] << endl; /// outputs one name.
    //}
}
posted May 1, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Make random return string. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a for loop.

string random(string names[]){
    int randNum = 0;
    randNum = rand() % 20 + 1;
    return names[randNum];
}
answer May 1, 2016 by Rajan Paswan
...