Reputation: 4607
I have the following application written in C:
The application basically presents the user with a word containing one incorrect letter. The user is requested to provide the position of the incorrect letter and replace it with a new letter.
The problem is that if I try to change letter number 4 (array index 3), the new word would be Act instead of Actually. If I do it programmatically, that is, change this line
string[letter_number - 1] = change;
to this
string[letter_number - 1] = 'u'
everything works fine. How can I solve this problem please? Thanks.
Upvotes: 1
Views: 3041
Reputation: 2753
Matthew,
Basically I tested your code in GCC compiler. I was in need to change the following things to make it work
scanf_s("%c\n", &change); //Change this as below
scanf("%c", &change);
PS: Please be aware that fflush(stdin) wont work with GCC.
Upvotes: 0
Reputation: 4366
Replace your scanf_s
by a simple scanf
and you will be done. Or else you can use
scanf_s("%d ", ...);
and remove the getchar();
This works for me :
#include <string.h>
#include <stdio.h>
int main()
{
char string[9] = "Actwally";
int letter_number;
char change;
printf("---Spot the Odd Letter Out---\n\n");
printf("The word below contains one letter which is incorrect:\n\n");
printf("Word: %s\n\n\n", string);
printf("Please provide the position of the incorrect letter and propose a new letter\n\n");
printf("Position of incorrect letter: ");
scanf("%d ", &letter_number);
printf("\nProposed new letter: ");
scanf("%c ", &change);
string[letter_number - 1] = change;
printf("\n\nThe new word looks like this %s\n\n\n", string);
if(strcmp("Actually", string) == 0)
{
printf("You are right! Congratulations!");
}
else
{
printf("Sorry, but you have not guessed the word. Better luck next time!");
}
printf("\n\n\nPlease press enter to exit the program");
getchar();
}
Upvotes: 1
Reputation: 399803
Verify that your inputs are correct before using them. It sounds as if change
gets set to 0, terminating the string.
I'm not sure about your getchar()
calls between the scanf()
calls, they could lose input.
Upvotes: 0