1

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!";
3
  • 1
    Do you have a program that takes an input and replies with a "random" fixed string all the time? Commented Jan 4, 2011 at 12:40
  • Yes, my problem was to hardcode my answers and to Randomize it Commented Jan 4, 2011 at 16:16
  • printf("%s\n", sa[rand() % 2]); Commented Jan 28, 2022 at 15:41

5 Answers 5

5
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

Sign up to request clarification or add additional context in comments.

1 Comment

const char *sa[] would be better.
3
#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;
}

Comments

2

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];

Comments

1

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;
}

Comments

0

#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; }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.