fgets don't work as I expected with this code

Feb 23, 2012 at 11:19pm
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);


}

Last edited on Feb 24, 2012 at 1:46am
Feb 23, 2012 at 11:24pm
Is there a newline that you're grabbing instead of ignoring?
Feb 23, 2012 at 11:41pm
Thanks for your answer.I press "enter" key after writing the text,other then that I don't think there is a newline...

Additionally,I forgot to say that it is always the last word of the sentence which a newline is put after,before "ay".
Last edited on Feb 23, 2012 at 11:46pm
Feb 23, 2012 at 11:44pm
Yes, I think your program is reading the new line character(s) when you press enter. I'll bet if you press space before enter it will do something you wouldn't expect...
Feb 24, 2012 at 12:10am
Thanks for your answer.Is it possible to fix this problem?(other than using gets?
Last edited on Feb 24, 2012 at 12:11am
Feb 24, 2012 at 10:19pm
Using word=strtok(NULL," \n"); instead of word=strtok(NULL," "); solved my problem...
Topic archived. No new replies allowed.