0

so the program works except for one part of it.

I really dont understand why its not outputting the correct thing. Also i have to use the strtok, strcmp, and fgets functions. So i cant change those.

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

 int main(){

 char a[256];

 while(x==0){//this will loop until the exit cammand is given

 int y = (strcmp(fgets(a, 256, stdin), "exit\n")); 
 char* token = strtok(a, " ");
 int numOfTokens = 0;

 if (y == 0){
 exit(0);
 }
 else{
 printf("Line read:%s\n", a);
 printf("Token(s):");
 while(token != NULL){
 numOfTokens +=1;
 printf("\n%s", token);
 token= strtok(NULL, " ");
 }
 printf("%i token(s) read\n", numOfTokens);
 }
 }
 return 0;
 }

So everything is entered from a linux terminal. the output should be:

 `h e l l o//input
 //output as followed
 Line read:h e l l o
 Token(s):
 h
 e
 l
 l
 o
 5 token(s) are read`

but when i do the thing that messes up is:Line read:h how would i make it where it prints the whole line that the user inputs

Damion Owens
  • 25
  • 1
  • 7

1 Answers1

1

move strtok() to after the printf().
Reason is that strtok() changes its argument so you print the changes.

instead of

... strtok(a, " ") ... ;
... printf("%s", a) ... ;

do

... printf("%s", a) ... ;
... strtok(a, " ") ... ;
pmg
  • 106,608
  • 13
  • 126
  • 198