In: Computer Science
Why is my C code counter returning the wrong output?
void removeLn(char *tPtr) {
for (; *tPtr != '\0'; tPtr++) {
if (*tPtr == '\n') {
*tPtr = '\0';
}
}
}
This is a method I wrote that essentially replaces the \n in a text
file with a null.
int counter(FILE *filePtr) {
char ln[length];
int counter = 0;
while (fgets(ln, length, filePtr) != NULL) {
char *r;
for (r = ln; *r != '\0';) {
while (isspace(*r)) {
r++;
}
if (*r == '\0') {
break;
} else {
count++;
}
r++;
}
return(counter);
}
}
This function goes through a text file, goes past spaces, stops if
it points to null, increments count for each word in the text file,
and goes until it points to neither a space or a null.
This code is giving me two different outputs. For instance, if a test txt file is 19 characters, if I call it with ./counter and then input the file path, I get 18. However, if I run it ./counter example.txt, I'll get 12. I can't make it out why and where it's wrong. Any help would be a big help...
EDIT: I changed == to = and now both answers are consistent and I am short by 7. 12 is now actual, 19 expected
Example Output:
Why hello there friend.
How are you doing today.
I am doing honestly *very* well,
The sun is coming!
Expected 19
Actual 12
The code is upto the mark the issue is with this line :
fgets(ln, length, filePtr) => This will only read the single line from file not the whole text.
Instead of this you can use :
getc(filePtr) => This will get each character at a time from the file and the whole text in the file will be covered.
Use this to fill the ln array :
ind=0;
for (c = getc(filePtr); c != EOF; c = getc(filePtr))
{
ln[ind++]=c;
}
Now when you print char array ln you will get the full paragraph (It will be considered as a single string only,check the below attached images for clarification)
Also for each '\n' character you changing it to '\0' which will break your code as soon as the very first line will get complete. Due to the below statement :
if (*r == '\0') {
break;
}
Which is wrong your program must run till the end of whole file but it will stop as soon as the first line terminates
You can check the Sample Output in both cases :
Here is the simple code to do your task without using removeLn function :
#include <stdio.h>
#include <ctype.h>
#define MAX_FILE_NAME 100
int ans =0 ;
int counter_mod(char *fp)
{
while(*fp != '\0'){
if(isspace(*fp))
ans++;
fp++;
}
// printf("aaab");
return ans - 1 ;
}
int main()
{
FILE *fp;
int count = 0;
char filename[MAX_FILE_NAME];
printf("Enter file name: ");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 0;
}
char ln[1000],c;
int ind=0;
for (c = getc(fp); c != EOF; c = getc(fp))
{
ln[ind++]=c;
}
char * r = ln ;
printf("%d",counter_mod(r));
return 0;
}
I hope this will help you understand why the program gives wrong output.
Feel free to ask any further doubts or anything you need to get more clarified I will be very happy to help you.