简体   繁体   中英

String is adding special characters

I started following tutorials on C, and then I (from scratch) attempted to do a program where the program chooses a word and you have to guess letters, until you find out the word or run out of attempts.

But I am stuck at the string part, really weird :

srand(time(NULL));
char pWord[6][15] = {"chocolate","peanut","bowling","helicopter","school","controller"}; // Possible words
int repeat=0;
int rNum = rand()%6;
char solution[strlen(pWord[rNum])];
while(repeat<strlen(pWord[rNum])) {
    solution[repeat]=pWord[rNum][repeat];repeat++;  
}
printf("Answer : %s", solution); printf("\n");
printf("R Answer : %s", pWord[rNum]); printf("\n");
printf("R length : %i", strlen(pWord[rNum])); printf("\n");
strcpy(solution,pWord[rNum]);

For bowling it is fine, but for others it adds weird special characters at random.
I have no idea why this is happening ( i come from java, somewhere lazy and easy ).

In C, the string ends with null character '\\0' . So when you declare the character string solution , you need to add one to the length of the char array since strlen() function doesn't count the null character at the end.

char solution[strlen(pWord[rNum])+1];

Then after the while loop, you need to assign the '\\0' to the last element of the char array:

while(repeat<strlen(pWord[rNum])) {
    solution[repeat]=pWord[rNum][repeat];
    repeat++;  
}
solution[repeat]='\0';

A better way to do this string copying is to use strcpy() function instead of the while loop:

strcpy(solution, pWord[rNum]);

This way you don't have to assign the null character to the last character. This function does it for you.

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