CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #1
    Join Date
    Oct 2009
    Posts
    40

    [RESOLVED] fgets don't work as I expected with this code,need help

    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:

    "
    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.
    After minutes/hours of investigation,I have found that the problematic part is fgets.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.

    #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,"&#37;s%s",plat,"ay");

    memmove(plat,&plat[1],strlen(plat));

    printf("%s\n",plat);


    }
    Last edited by AwArEnEsS; February 23rd, 2012 at 08:48 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured