Reputation: 1536
My task is to check the user input and replace each period with exclamation mark, and each exclamation mark with 2 exclamation marks, then count the number of substitutions made.
This is my code:
int main(void)
{
int userInput, substitutionsNum = 0;
printf("please enter your input:\n");
while ((userInput = getchar()) != '#')
{
if (userInput == '.')
{
userInput = '!';
++substitutionsNum;
}
else if (userInput == '!')
{
userInput = '!!';
++substitutionsNum;
}
}
printf("%c, the number of substitutions are: %d", userInput, substitutionsNum);
return 0;
}
If I put in the input "nir." and then "#" to go out of the program, the output is "#, the number of substitutions are: 1"
Upvotes: 4
Views: 1664
Reputation: 6121
!!
is two characters. You assume it as a single character.
And you are overwriting the in the same variable userInput
You could use one more char buffer so that you can adjust your indices according to need. for example two increment to index when you want to store "!!".
Upvotes: 1
Reputation: 400049
You never print the input back out except once at the end, so the "replacement" won't work.
Also, you can't represent a pair of exclamation points as '!!'
, that's a multi-character literal which is not the same. At least, no I/O functions will do what you expect with it, if you try to print it for instance.
Upvotes: 2
Reputation: 181430
You are doing it wrong. You need to store the accumulated changed input in a character array (i.e. char buffer[1024]
) and place the substitutions there. With your algorithm, the only thing you are going to print is the last value of userInput
variable.
Since this is probable homework I would suggest you to read more about string manipulation in C language.
Upvotes: 0