简体   繁体   中英

How to assign a single character from a string to another string in C?

I have

char alphabet[27] = {"abcdefghijklmnopqrstuvwxyz"};

and I want to assign a random letter from the above string to a string called

char guess[2]

This is what I have so far:

    srand(time(NULL));
    int r = rand() % 28;
    char strcpy(guess, alphabet[r]);

I know this won't work because it will try to copy the whole alphabet into guess right? I just want to assign a random letter to guess so I can create a hangman program and I want the PC to guess the letters to the secret word. In a previous version of the program, I was the one to guess the letters so I just used

gets(guess);

to do it. I want it to be the same but with the PC guessing random letters from the alphabet string. Is that possible?

Just forgo any form of strcpy :

srand(time(NULL));
int r = rand() % 26;
guess[0] = alphabet[r];
guess[1] = '\0';

But if you want to use it just as a char , and not an array, just declare char guess; and use it as such.

I know this won't work because it will try to copy the whole alphabet into guess right?

Right on the "wouldn't work", but not exactly right on the why part: it will try using alphabet[r] as an address , which will cause undefined behavior.

Getting a single char is much simpler than that - you do not need a function, you can do this:

char guess = alphabet[r];

That's it - a single char can be copied with a simple assignment.

In a previous version of the program, I was the one to guess the letters so I just used gets(guess)

This explains why you declared guess as char[2] , not as char . You do not need to do it like this in this version of the program, because you are not reading the input, so you don't need an extra spot for the null terminator.

Also note that gets should not be used - it is inherently unsafe, because it can easily cause buffer overruns. You should use fgets instead, because you can pass the size of the buffer to fgets , and ensure that it wouldn't go past the end of your buffer.

Why not just do something like

guess[0] = alphabet[r];

?

Just as you can read a single character from the array alphabet with alphabet[index] you can set a single character in the same way as well, so:

guess[0] = alphabet[r];

To make sure guess can be used as a NUL-terminated string you'll need to make sure the second char is NUL:

guess[1] = '\0';

A final bug in your code is in the following line:

int r = rand() % 28;

The 28 needs to be replaced by 26 (there are only 26 valid values).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM