I'm not well versed in c and I'm having issues with
given a string like "abcda", I want to count the number of "a"s and return the count
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char** argv){
char* string_arg;
int counter = 0;
if(argc == 2){
for(string_arg = argv[1]; *string_arg != '\0'; string_arg++){
printf(string_arg);
printf("\n");
/*given abcda, this prints
abcda a
bcda b
cda but i want c
da d
a a */
if(strcmp(string_arg, "a") == 0){ //syntax + logical error
counter++;
}
}
printf(counter);
}
else{
printf("error");
}
return(0);
}
I'm also not supposed to use strlen()
How do I compare one character at a time, correctly?
if (strcmp(string_arg, "a") == 0) {
counter++;
}
The call to strcmp
is not appropriate in your case, as it compares strings. With this statement you compare a string starting at the element pointed to by string_arg
with the string "a"
, not the character constant 'a'
. Note that "a"
is equal to 'a'
+ '\0'
.
Instead, You need to compare *string_arg
with 'a'
:
if (*string_array == 'a') {
counter++;
}
puts(string_arg);
prints a string. That is not what you want. You want to print only a single character. Use printf("%c", *string_arg);
instead to print a character.
Note that something like printf(string_arg);
is dangerous. Always use a format specifier: printf("%c", *string_arg);
. Reasony why is explained under the following link:
Why is printf with a single argument (without conversion specifiers) deprecated?
This shall be what you want:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main (int argc, char** argv) {
char* string_arg;
int counter = 0;
if (argc == 2){
for (string_arg = argv[1]; *string_arg != '\0'; string_arg++) {
printf("%c", *string_arg);
printf("\n");
if (*string_arg == 'a') {
counter++;
}
}
printf("%d times character 'a' encountered.", counter);
}
else {
printf("Error: No second argument at the program invocation!");
}
return 0;
}