简体   繁体   中英

How to change individual characters in string on C?

Trying to make some basic hangman code to practice learning C but I can't seem to change individual characters in the program

int main(int argc, char *argv[]) {
    int length, a, x;
    x = 0;
    char gWord[100];
    char word[100] = "horse";

    length = strlen(word) - 1;
    for(a = 0; a<= length; a = a + 1){
        gWord[a] = "_";
        printf("%s", gWord[a]);
    }
    printf("%s", gWord);
}

when I try to run this it just prints (null) for every time it goes through the loop. It's probably a basic fix but I'm new to C and can't find anything about it online

To print character instead of string change:

printf("%s", gWord[a]);

to:

printf("%c", gWord[a]);

but before that change also:

gWord[a] = "_";

to:

gWord[a] = '_';

The last problem is that you were assigning a string literal to a single character.

Edit:

Also as @4386427 pointed out, you never zero-terminate gWord before printing it later on with printf("%s", gWord) . You should change the last line from:

printf("%s", gWord);

to:

gWord[a] = '\0';
printf("%s", gWord);

because otherwise this would very likely lead to a buffer overflow.

This line

printf("%s", gWord[a]);

Must be

printf("%c", gWord[a]);

To print a char, c is the right specifier. s is only for whole strings and takes char pointers.

Are you getting any warning message('s) when compiling your code?

Since you are learning C language, one suggestion - Never ignore any warning message given by the compiler, they are there for some reason.

Three problems in your code:

First:
Assigning string to a character:

gWord[a] = "_";

gWord is an array of 100 characters and gWord[a] is a character at location a of gWord array. Instead, you should do

gWord[a] = '_';

Second:
Using wrong format specifier for printing a character:

printf("%s", gWord[a]);
        ^^

For printing a character you should use %c format specifier:

printf("%c", gWord[a]);

Third:
Missed adding null terminating character at the end in gWord and printing it:

printf("%s", gWord);

In C language, strings are actually one-dimensional array of characters terminated by a null character '\\0' . The %s format specifier is used for character string and by default characters are printed until the ending null character is encountered. So, you should make sure to add '\\0' at the end of gWord after the for loop finishes:

gWord[a] = '\0';

Apart from these, there are couple of more things -
This statement:

length = strlen(word) - 1;

I do not see any reason of subtracting 1 from the word length. The strlen return the length of string without including the terminating null character itself. So, the strlen(word) will give output 5 . Now you are subtracting 1 from this and running loop till <= length may confuse the reader of the code. You should simply do:

    length = strlen(word);
    for(a = 0; a < length; a = a + 1){
     ....
     ....

Also, the return type of strlen() is size_t and the size_t is an unsigned type. So, you should use the variable of type size_t to receive strlen() return value.

Last but not least, make sure to not to have any unused variables/parameters in your program. You are not using argc and argv anywhere in your program. If you are using gcc compiler then compile it with -Wall -Wextra options. You will find that compiler will report all the unused variables/parameters. So, if not using argc and argv then you should simply give void in the parameter list of main() function.

Putting these all together, you can do:

#include <stdio.h>
#include <string.h>

int main(void) {
    size_t length, a;
    char gWord[100];
    char word[100] = "horse";

    length = strlen(word);
    for(a = 0; a < length; a = a + 1) {
        gWord[a] = '_';
        printf("%c", gWord[a]);
    }

    gWord[a] = '\0';
    printf ("\n");
    printf("%s\n", gWord);
    return 0;
}

Syntactically, your code is alright @Blookey. But logically, no actually.

Let me point out 3 places which are causing the undesired behavior in your code:

  1. gWord[a] = "_"; Observe this line. You have specified the _ in " " . In case you are unaware of this fact, each individual element of a string is a character. And each character is supposed to be given in ' ' , ie, single quotes and not double quotes.
  2. printf("%s", gWord[a]); A similar error again. gWord[a] is a character, not a string. Hence you need to print it using the format specifier %c instead of %s which is for string instead.
  3. A string, any string is supposed to end with a NULL, which is \\0 (backslashZERO). That is what differentiates an array of characters from a string. So just add the following line once you finish loading characters into gWord[] .

    gWord[a] = '\\0';

Here is the complete code, just with the 3 changes:

#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[]) {
    int length, a, x;
    x = 0;
    char gWord[100];
    char word[100] = "horse";

    length = strlen(word) - 1;
    for(a = 0; a<= length; a = a + 1){
        gWord[a] = '_';
        printf("%c ", gWord[a]);
    }
    gWord[a] = '\0';
    printf("\n%s", gWord);
}

Here is the OUTPUT:

_ _ _ _ _ .

_____.

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

int main(int argc, char *argv[]) {
int length, a, x;
x = 0;
char gWord[100] = {0};
char word[100] = "horse"; /*note that if the array in place strlen +1 is not nulled  before using strlen you might not get the correct result*/

length = strlen(word) - 1;/*strln will return 5, that is the letters inn the string the pointer is pointing to until the first terminator '\0'*/
for(a = 0; a<= length; a = a + 1){
gWord[a] = '_'; /* if you use "_" it will try to fit in the chars '_' and '\0' to each char slot of the array*/
printf("%c", gWord[a]); /* %s looks for a string to print while here there are single chars to print*/
}
printf("\n");/*you can print the hole string like this */
printf("%s", gWord); 

return 0;/*and remember that main function should always have a return value*/
}

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