0

I couldn't print the whole output in a string.

All I know is that %s should work like a loop for example printf("%s", str); works the same as puts(str);

#include <stdio.h>
#include <string.h>


int main (){
    char str[]="Hello:, student; how are you? This task is easy!";
    char *token;
    char del[] = ", ; : ? !", cp[80];
    int count;
    strcpy(cp, str);
    token = strtok(str, del);
    count = 0;
    while( token != NULL )
    {
        printf("%s\n", token);

        token = strtok(NULL, del);
        count++;
        }   
    strtok(str, del);   
    printf("Your sentence has %d words\n", count); 
    puts("The sentence without punctuation charachters is: \n ");
    puts(str); // This should where it show me the output
    return 0 ;
}

// I tried to follow the instruction I had to write this code in this form. // This is the output that I suppose to get

Hello

student

how

are

you

This

task

is

easy

Your sentence has 11 words The sentence without punctuation characters is: Hello student how are you This task is easy

// all I got is ( ignore the extra line between each word)

Hello

student

how

are

you

This

task

is

easy

Your sentence has 11 words The sentence without punctuation characters is: Hello

19h
  • 9
  • 1

1 Answers1

0

strtok(str, del); modifies its first parameter adding null characters inside, this is why when you print str after the calls of strtok you got only the first token

you save the string doing strcpy(cp, str); but you do not use it, and you also hope 80 is enough ...

A proposal placing the words in cp then printing it :

#include <stdio.h>
#include <string.h>

int main (){
  char str[]="Hello:, student; how are you? This task is easy!";
  char *token;
  char del[] = ", ; : ? !", cp[sizeof(str) + 1];
  int count;
  size_t pos = 0;

  token = strtok(str, del);
  count = 0;
  while( token != NULL )
  {
    printf("%s\n", token);
    strcpy(cp + pos, token);
    pos += strlen(token);
    cp[pos++] = ' ';
    token = strtok(NULL, del);
    count++;
  }
  cp[(pos == 0) ? 0 : (pos - 1)] = 0;
  printf("Your sentence has %d words\n", count); 
  puts("The sentence without punctuation characters is:");
  puts(cp); // This should where it show me the output
  return 0 ;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Hello
student
how
are
you
This
task
is
easy
Your sentence has 9 words
The sentence without punctuation characters is:
Hello student how are you This task is easy
pi@raspberrypi:/tmp $ 
bruno
  • 32,421
  • 7
  • 25
  • 37
  • Is there any other way to do it? I don't know what " size_t pos = 0; " and " cp[(pos == 0) ? 0 : (pos - 1)] = 0; " do. – 19h Apr 20 '19 at 15:29