Question

In: Computer Science

Why is my C code counter returning the wrong output? void removeLn(char *tPtr) { for (;...

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

Solutions

Expert Solution

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.


Related Solutions

why my code for mergesort always wrong ? void Merge(vector<int>& data, int p, int q, int...
why my code for mergesort always wrong ? void Merge(vector<int>& data, int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; vector<int>left(n1); vector<int>right(n2); for(int i = 0; i < n1; i++) { left[i] = data[p + i]; } for(int j = 0; j < n2; j++) { right[j] = data[q+j+1]; } int i = 0; int j = 0; for(int k = p; k <= r; k++) { if(left[i]...
In Java What is the output produced by the following code? char letter = 'B'; switch...
In Java What is the output produced by the following code? char letter = 'B'; switch (letter) { case'A': case'a': System.out.println("Some kind of A."); case'B': case'b': System.out.println("Some kind of B."); break; default: System.out.println("Something else."); break; }
This is the code I have. My problem is my output includes ", 0" at the...
This is the code I have. My problem is my output includes ", 0" at the end and I want to exclude that. // File: main.cpp /*---------- BEGIN - DO NOT EDIT CODE ----------*/ #include <iostream> #include <fstream> #include <sstream> #include <iomanip> using namespace std; using index_t = int; using num_count_t = int; using isConnected_t = bool; using sum_t = int; const int MAX_SIZE = 100; // Global variable to be used to count the recursive calls. int recursiveCount =...
C++ Write the C++ code for a void function that prompts the user to enter a...
C++ Write the C++ code for a void function that prompts the user to enter a name, and then stores the user's response in the string variable whose address is passed to the function. Name the function getName.
C++ program. Please explain how the code resulted in the output. The code and output is...
C++ program. Please explain how the code resulted in the output. The code and output is listed below. Code: #include <iostream> #include <string> using namespace std; int f(int& a, int b) {    int tmp = a;    a = b;    if (tmp == 0) { cout << tmp << ' ' << a << ' ' << b << endl; }    b = tmp;    return b;    return a; } int main() {    int a...
I have an unexpected indent with my python code. please find out whats wrong with my...
I have an unexpected indent with my python code. please find out whats wrong with my code and run it to show that it works here is the code : def main(): lis = inputData() customerType = convertAcct2String(lis[0]) bushCost = getBushCost(lis[0],int(lis[1],10)) flowerCost = getFlowerBedCost(int(lis[2],10),int(lis[3],10)) fertiCost = getFertilCost(int(lis[4],10)) totalCost = calculateBill(bushCost,fertiCost,flowerCost) printReciept(customerType,totalCost,bushCost,fertiCost,flowerCost) def inputData(): account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage = input("Please enter values").split() return [account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage] def convertAcct2String(accountType): if accountType== "P": return "Preferred" elif accountType == "R": return "Regular" elif accountType == "N": return...
code in. c++ void seen ); If there is already a Word object in the Words...
code in. c++ void seen ); If there is already a Word object in the Words list, then the number of occurrences for this word is incremented. If there is no Word object for this word already, create a new word object with occurrence =1, and insert this object into the list of Word objects. getNextWord(); Returns the next word of the list and sets the currentItem pointer to the next Word. This may return an empty string, “”, if...
Below is my code in C#, When I run it, the output shows System.32[], Can you...
Below is my code in C#, When I run it, the output shows System.32[], Can you please check and let me know what is the problem in the code. class Program { static void Main(string[] args) { int number=12; Console.WriteLine(FizzArray(number)); } public static int[] FizzArray(int number) { int[] array = new int[number]; for (int i = 1; i < number; i++) array[i] = i; return array; }
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using namespace std; const int CWIDTH = 26; int main() {    int choice;    double convertFoC, converCtoF;    double starting, endvalue, incrementvalue;    const int CWIDTH = 13;    do {       cin >> choice;    switch (choice)    {        cin >> starting;    if (starting == 28){       cout << "Invalid range. Try again.";    }    while (!(cin >> starting)){       string  garbage;       cin.clear();       getline(cin, garbage);       cout << "Invalid data Type, must be a number....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT