I have a problem with the codes below.I am trying to do an exercise from a C book.My code first asks for user input,then it seperates the given input into it's "atoms".Then it changes the words like this:Let's say one of the word is "soccer",my program tries to change it to "occersay",it puts the first letter of the word after the last
letter of the word and it adds "ay" to the last part of the word.
But the problem is,if I use
fgets
for asking user input,it runs as this:
1 2 3 4 5 6
|
Please write a sentence without using any punctuator: We play soccer
eWay
laypay
occer
say
|
As you see,it automatically passes to newline before putting "s" and "ay" after the "occer",though it works well
with previous words.
If I use
gets(sentence)
instead of
fgets(sentence,50,stdin)
then no problem,it works as I expected.
Is there a way to do same thing with
fgets
?I have read on internet that
gets
has not been a type-safe function and it was recommended to use
fgets
instead of
gets
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void lwords(char*);
int main()
{
char* sentence=(char*) malloc(150);
printf("Please write a sentence without using any punctuator: ");
fgets(sentence,50,stdin);
char* word=strtok(sentence," ");
while (word!=NULL)
{
lwords(word);
word=strtok(NULL," ");
}
free(sentence);
}
void lwords(char* word)
{
char* plat=(char*) malloc(40);
strcpy(plat,word);
int stringsize=strlen(plat);
memmove(&plat[strlen(plat)],&plat[0],1);
plat[(stringsize+1)]='\0';
sprintf(plat,"%s%s",plat,"ay");
memmove(plat,&plat[1],strlen(plat));
printf("%s\n",plat);
}
|