Reputation: 169
In this program, I want to print out the instance of different characters in a file. The output will contain three variable, the number of occurrence, the hex of the letter, and the letter itself. Can someone help me with this? I am stuck!
Results of program should be something like this:
10 instance of character 0x4s (O)
10 instance of character 0x51 (W)
10 instance of character 0x51 (Y)
2 instances of character 0x65 (a)
18 instances of character 0x67 (c)
16 instances of character 0x81 (d)
//here is my program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char FILE_NAME[] = "input.txt";
int main(argc, *argv[]) {
char temp;
char count[255];
FILE *in_file;
int ch;
fp = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Can not open %s \n", FILE_NAME);
exit(0);
}
while (!feof(fp)) {
ch = fgetc(fp);
if(strchr(count, ch)!= NULL)
{
}
}
printf("%d instance of character (%c)", count);
fclose(in_file);
return (0);
}
Upvotes: 0
Views: 505
Reputation: 10107
Here's what you want (based on your code, with many comments by me):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> // you need this to use isupper() and islower()
const char FILE_NAME[] = "input.txt";
int main(int argc,char *argv[]) {
char temp;
unsigned count[52] = {0}; // An array to store 52 kinds of chars
FILE *fp;
int i;
fp = fopen(FILE_NAME, "r");
if (fp == NULL) {
printf("Can not open %s \n", FILE_NAME);
exit(0);
}
while((temp = fgetc(fp)) != EOF) { // use this to detect eof
if(isupper(temp))
count[26+(temp-'A')]++; // capital letters count stored in 26-51
if(islower(temp))
count[temp-'a']++; // lower letters count stored in 0-25
}
fclose(fp); // When you don't need it anymore, close it immediately.
for(i = 0; i < 26; i++)
if(count[i])
printf("%d instance of character 0x%x (%c)\n", count[i], 'a'+i, 'a'+i);
for(; i < 52; i++)
if(count[i])
printf("%d instance of character 0x%x (%c)\n", count[i], 'A'+i-26, 'A'+i-26);
return (0);
}
Upvotes: 1
Reputation: 399793
Your array count
is not a string, so using strchr()
on it is not a good idea. Also, it's of type char
, so it has very limited range for larger files.
You should probably use something like unsigned long count[256]
. Make sure to initialize the counts to 0 before starting.
Also, don't use feof()
. Just loop calling fgetc()
until the returned character (which, correctly, has type int
) is EOF
. Cast it to something positive before using it to index into count
for the increment.
Upvotes: 0