I'm having a little problem modifying an array in C. I have two arrays, c1 and c2.
I want to manually fill the array c2
by typing the words array c1
contains. The user types a letter and if this letter is found in c1, the program fixes this letter in the appropriate place in c2. If the letter doesn't belong to c1, it does nothing. It's just like a "guess the word" game. Here is a sketch:
c1 = MARRON
c2: ******
Type a letter: E
c2: ******
Type a letter: A
c2: *A****
Type a letter: O
c2: *A**O*
Type a letter: P
c2:*A**O*
Type a letter: M
c2: MA**O*
Type a letter: N
c2: MA**ON
Type a letter: R
c2: MARRON
You win.
My code doesn't really following the sketch above. My problem is printing the asterisks and the letters at the right time. I also found out that the program replaces the last character '\\0'
with an asterisk even though i kept a condition to prevent that. Here' my code:
void complete( char *c2, char c1[], int letter ) {
int i = 0;
for( i = 0; i < strlen( c1 ) - 1; i++ )
if( c1[ i ] == '\0' ) {
c2[ i ] = '\0';
}
else if( letter != c1[ i ] && c2[ i ] != '*' );
else if ( letter == c1[ i ] ) {
c2[ i ] = letter;
c2[ i + 1 ] = '\0';
}
else if (letter != word[ i ] )
c2[ i ] = '*';
c2[ i + 1 ] = '\0';
}
int main(){
char c1[] = "ORANGE";
int length = strlen(c1);
char *c2 = NULL;
c2 = malloc(length * (sizeof(c1));
while( 1 ){
printf( "What is the secret word?: ");
printf( "%s\n", c2 );
printf( "Propose a letter: ");
letter = lirecaracter();//it just reads a character
char *suite = NULL;
suite = strchr(c1, letter );
if( suite != NULL ){
complete( c2, c1, letter );
}
if( strcmp( c1, c2 ) == 0 ){
printf( "\n You won, congrats\n" );
exit( 0 );
}
}
}
Thanks.
Pseudocode:
WordGuessGame(target[1..n], buffer[1..n], input[1..m])
1. for i := 1 to n do
2. buffer[i] := '*'
3. print buffer
4. for i := 1 to m do
5. for j = 1 to n do
6. if target[j] = input[i] then
7. buffer[j] := input[i]
8. if buffer = target then
9. print "You win!"
10. return
11. else print buffer
12. print "You lose..."
a solution for your homework is very simple like:
int main(){
char *p,c,*c1 = "ORANGE", c2[]="******";
while( puts(c2),strcmp(c1,c2) )
{
printf( "Propose a letter: ");
c=getchar(); while( getchar()!='\n' );
p=c1;
while( *p )
if( *p++==c ) c2[p-c1-1]=c;
}
printf( "\n You won, congrats\n" );
return 0;
}
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.