Thread: Strings

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    14

    Strings

    I am having a problem with my program. Whenever I input a 10 letter word like montgomery its' output is montgomer@ies. The program is about converting the noun that ends with "y" to "ies".
    Code:
    include <stdio.h>
    #include <string.h>
    #define STRING_LEN 20
    void check_noun(char *dest, const char *source);
    int
    main(void)
    {
    char original[STRING_LEN], changed[STRING_LEN];
    printf(" Please enter the noun here> ");
    scanf("%s", original);
    check_noun(changed, original);
    printf(" The plural version of noun is: %s\n ", changed);
    return(0);
    }
    void check_noun(char *dest, const char *source)
    {
    int num, number;
    for(num=0; num < strlen(source); num=num+1)
    {
    if(source[num]=='y')
    {
    strncpy(dest, source, num);
    strcat(dest, "ies");
    }
    }
    }
    Here is what happens when I run the program:
    Please enter the noun here> montromery
    The plural version of noun is: montromer@ies

  2. #2
    Registered User
    Join Date
    Mar 2012
    Location
    the c - side
    Posts
    373
    strcat uses the nul character to align the strings, and since
    you haven't copied the nul to the new string in strncpy()
    you need to insert your own first, so use

    Code:
    strncpy(dest, source, num);
    dest[num] = '\0';
    strcat(dest, "ies");

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by muradyan14 View Post
    The program is about converting the noun that ends with "y" to "ies".
    So, why do you check every letter if you only want to change the 'y' at the end of a string?

    For example try your program with a word like "physician".

    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-16-2012, 06:08 AM
  2. Swapping strings in an array of strings
    By dannyzimbabwe in forum C Programming
    Replies: 3
    Last Post: 03-03-2009, 12:28 PM
  3. malloc() strings VS array strings
    By Kleid-0 in forum C Programming
    Replies: 5
    Last Post: 01-10-2005, 10:26 PM
  4. Table mapping Strings to Strings
    By johnmcg in forum C Programming
    Replies: 4
    Last Post: 09-05-2003, 11:04 AM
  5. converting c style strings to c++ strings
    By fbplayr78 in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 03:13 AM