'generate random letter from word in c - my coding seems to not work
My output is blank. I'm trying to get a random letter from a user entered word. Any help?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (void) {
srand((unsigned int)(time(NULL)));
int i = 0;
char char1[31];
printf("Enter a word with 30 or fewer characters (no spaces):\n ");
scanf("%c", &char1[51]);
for(i = 0; i < 1; i++)
{
int num =
printf("Your random character is: %c", char1[rand() % (sizeof char1)]);
}
return 0;
}
Solution 1:[1]
scanf("%c", &char1[51]); is undefined behavior as char1 only have 31 bytes allocated. The other issue is that you use sizeof() which would return 31 even if you only read in, say, 3 characters. In this case there would be a 1 - 3/30 = 90% chance of returning uninitiated data, and this may very well be \0 which would not print anything. Use strlen() instead of sizeof() to get length of the string you just read into char1.
Here is a minimal working program (scanf ensures at least 1 byte is read, otherwise you need to check for that special case):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define LEN 30
#define str(i) xstr(i)
#define xstr(i) #i
int main() {
srand(time(NULL));
printf("Enter a word with %d or fewer characters (no spaces): ", LEN);
char char1[LEN + 1];
scanf("%" str(LEN) "s", char1);
printf("Your random character is: %c\n",
char1[rand() % strlen(char1)]);
return 0;
}
Example output:
Enter a word with 30 or fewer characters (no spaces): abc
Your random character is: a
Enter a word with 30 or fewer characters (no spaces): abc
Your random character is: c
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
