Handsken
Handsken

Reputation: 674

Random string from an array in c

I'm kind of new to C, but not to programming. I'm trying to create a program that takes an input and replies with a random string that's already saved in an array (for example).

I'm not trying to create a random string, I want them to be "fixed", like in Java:

String [] sa; 
sa[0] = "Hello, World"; 
sa[1] = "Hi dude!";

Upvotes: 1

Views: 6936

Answers (5)

Raghava Vutukuri
Raghava Vutukuri

Reputation: 1

#include<stdio.h> #include<stdlib.h> int main(){ char str[7][100]={"hello1","hello2","hello3","hello4","hello5","hello6","hello7"}; printf("%s",str[rand()%7]); return 0; }

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

const char *sa[]={"Hello, World","Hi dude!"};

Then you can do

return sa[i];

The return value is char *
Just make sure i is within bounds

Upvotes: 5

Raphael Bossek
Raphael Bossek

Reputation: 1954

Here what your are looking for:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    char buffer[42];
    const char *mytext[] = {"A1", "A2", "A3"};
    scanf("%41s", buffer);
    srand(time(NULL));
    printf("Random text: %s\n", mytext[rand() % (sizeof(mytext) / sizeof(mytext[0]))]);
    return 0;
}

Upvotes: 1

jweyrich
jweyrich

Reputation: 32240

#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *messages[] = {
        "Hello!",
        "How are you?",
        "Good stuff!"
    };
    const size_t messages_count = sizeof(messages) / sizeof(messages[0]);
    char input[64];
    while (1) {
        scanf("%63s", input);
        printf("%s\n", messages[rand() % messages_count]);
    }
    return 0;
}

Upvotes: 3

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22064

It's not clear as to what you exactly want, but here is a brief description of how strings work in C.

There are no String like data type in C as you have in Java. You have to use array of characters. For an array of strings, you have to use two dimensional array of characters.

char myStrings[MAX_NUMBER_OF_STRING][MAX_LENGTH_OF_STRING];

Upvotes: 2

Related Questions