'How to reset this string scanning code for a new letter?
I'm in the middle of homework and nearly finish. This is my code
#include <stdio.h>
#include <stdlib.h>
void main()
{
char word[100],*ptr,input;
int count,i,n;
printf("Enter the word : ");
scanf("%[^\n]", word);
ptr = &word;
do
{
printf("Enter the letter : ");
scanf(" %c", &input);
if(input == '-'){
printf("Exit.");
return 0;
}
for(i=0;word[i] != '\0';i++)
{
if(*ptr == input)
count++;
ptr++;
}
printf("Has %d of '%c'",count,input);
printf("\n");
}while(input != '-')
}
This code will extract the number of letter in string
For example : If you input "WWWWooo" it will give you "has 4 of 'W'" and "has 3 of 'o'"
Code will exit when you put '-' letter.
Problem that I find is the 'count' value seems to remain the total of number of the first letter I want to find.
What I expect : "WWWWooo" will give "has 4 of 'W'" and "has 3 of 'o'"
What I get is "has 4 of 'W'" and "has 4 of 'o'". The count value didn't reset.
I tried to put count = 0;
on the top of do while loop and the output will always be 0 for the second letter scanned for.
How can I fix this?
Solution 1:[1]
I changed your code a bit, I guess this is what you're looking for (the comments in the code explain pretty much all the changes I've made):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char word[100],*ptr,input;
int count,i,n;
printf("Enter the word : ");
scanf("%99[^\n]", word); //changed to %99[^\n] to avoid buffer overflows
do
{
count=0; //count=0 should be here as count++ changes the value of count afterwards
ptr=word; //ptr=word should be here too since ptr++ changes the value of ptr afterwards
/* you might have probably gotten a compiler warning because
of ptr=&word, since &word is char(*)[100] (a pointer to an array of 100 chars)
and char(*)[100] and char * are quite different,
so you can either do ptr=word or ptr=&word[0] (both of which point to the first character in the array) */
//the rest of the code below is basically the same
printf("Enter the letter : ");
scanf(" %c", &input);
if(input == '-'){
printf("Exit.");
return 0;
}
for(i=0;word[i] != '\0';i++)
{
if(*ptr == input)
count++;
ptr++;
}
printf("Has %d of '%c'",count,input);
printf("\n");
}while(input != '-'); //you had missed a ';' here
}
The int main(void)
is because, quoting n1570 (emphasis mine):
It shall be defined with a return type of int and with no parameters: int main(void) { /* ... */ } or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): int main(int argc, char *argv[]) { /* ... */ } or equivalent
Even though I haven't checked the return value of scanf()
in the above code, but as mentioned by @Yunnosch in the comment, it's always a good idea to do so.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |