Hi I am struggling with a question. how do i find and output which one is most frequent from a given set of arguments on command line in c ? pls help. thanks
most repeating element in command line arguments
Collapse
X
-
You would need to keep your arguments in a place that is not destroyed after the program completes.
That would be in a file.
Write a function that creates this file if it does not exist and then goes on to write each command line argument to the end of the file. I suggest as a string with one string per record (\n).
Run your program several times and verify the file has captured all the command line argument.
Then write a second program to analyze the file. You should be able to count each time an argument was used regardless of where it appeared when the first program was run.
In the second program your problem is to read a file of strings and count each time a particular string was used.
There are several ways to do this. But rather than go into it now, let me know if you use this approach. If you do, and get stuck analyzing the file. Post again and I'll continue on. -
here is what i was trying
#include<stdio. h>
#include<stdlib .h>
#include<string .h>
int main(int argc , char * argv[]) {
int i,j;
int x=0;
for(i=1;i<argc; i++) {
for(j=i+1;j<arg c;j++) {
if(argv[i]==argv[j]) {
x++;
argv[i]=argv[j];
}
}
}
printf("The most frequent arg is ",i);
return 0;
}Comment
-
First, argv is an array of character pointers so this code:
will compare the addresses of the two strings. Since the strings are in different locations, the addresses will always be different. Use strcmp to compare the entire string.Code:if(argv[i]==argv[j]) etc...
You will need to make an array for the counts. The first element would be the count of the first argument.
Next, starting with argv[0], compare the string to each of the other arguments, and if equal, increment the count[0] of your counts array.
Repeat the above using argv[1] placing the count in count[1].
Do this argc -1 times. (the program name is counted as an argument but you want only the argv strings).Comment
Comment