Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with Char in c programming

Tags:

c

I am a newbie in c programming language and I have a university tutorial assignment that is related with working with chars(I wont be graded for this assignment) where you have to count words, I have to compile and submit my answers in an online web environment where my code will run against test cases that are not visible to me.here is my assignment:

Write the function 'wc' which returns a string containing formatted as follows: "NUMLINES NUMWORDS NUMCHARS NUMBYTES" . Whitespace characters are blanks, tabs (\t) and new lines (\n). A character is anything that is not whitespace. The given string is null-char (\0) terminated.

here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* wc(char* data) {
  char* result ;
  int numLine ;
  int numWords ;
  int numChars ;
  int i;
  int numBytes =strlen(data);
  char* empty=NULL;
  while(strstr(data,empty)>0){
    numWords=1;

    for (i = 0; i < sizeof(data); i++) {

    if(data[i]=='\n'){
     numLine++;
   }
    if(data[i]==' ' ){
     numWords++;
   }
    if(data[i]!=' '){
     numChars++;
   }
   }

   }

    sprintf(result, "%d %d %d %d", numLine, numWords, numChars, numBytes);
    return result;
}

this code will give me the correct output result but I am missing something here at least the test tells me that.

like image 742
Solix Avatar asked Nov 30 '25 08:11

Solix


2 Answers

You've got a very serious error:

  char* result;
  ...
  sprintf(result, "%d %d %d %d", numLine, numWords, numChars, numBytes);

This is not allowed in C. You need to allocate sufficient memory for the string first. Declare result as a large enough static array, or use malloc if you've covered that in your course.

e.g.

char buf[100];  // temporary buffer

sprintf(buf, "%d %d %d %d", numLine, numWords, numChars, numBytes);

char *result = malloc(strlen(buf) + 1);   // just enough for the string
strcpy(result, buf);                      // store the string

return result;
like image 121
teppic Avatar answered Dec 02 '25 20:12

teppic


What if you have this input?

Two        Words.

You have to count the transitions between whitespace/non-whitespace, not just count spaces.


Also, I'm pretty sure strstr(data,NULL) will not do anything useful.

like image 34
luser droog Avatar answered Dec 02 '25 21:12

luser droog