after numerous attempts to make my program work I turn to you guys. I want to make a program that counts the numbers of times a specific word has been typed in. That specific word has been specified as an argument and I’m trying to recall it by using argc and argv. Then I want the program to count the number of times I type in a word and to finish I want to be able to type in #EOF so it stops and shows me the result. This is what I have been trying on so far.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i=0;
char buf[1026]={'\0'};
char *p="#EOF\n";
fgets(buf, sizeof buf, stdin);
while((strcmp(buf, p) !=0) && (fgets(buf, sizeof buf, stdin) != NULL ))
{
if(strncmp(buf, argv[1], strlen(argv[1])) == 0)
{
i++;
}
}
printf("%d", i);
return 0;
}
I get no errors at all, but nothing really happens either. I did try to check where the fault lies, and I found out that when I try to display the value of I within the if statement it’s counting very very very fast!
Thanks in advance!
You have an infinite loop.
In the above line of code,
fgets()will take fromstdina string of characters including the newline character and store it intobuf.A simple fix to that is to add the newline character into the string you check against:
Other issues:
1)
2) Because you used a
while()loop, and you’re checking before getting any input, you’ll always enter it at least once. This might not be what you wanted to do. Ado/whileloop, or grabbing the input as the first step would be better.3)
if(strncmp(buf, argv[0],this is checking against the name of your program, if you wanted to check against the first command line argument you wantedargv[1]4) If you’re trying to check that the first command line argument is the same as what the user is typing you want this:
My version of your code that’s working: