STRNCAT Problem

This is a discussion on STRNCAT Problem within the C Programming forums, part of the General Programming Boards category; Hi, Thanks in advanced. Specs: C, Borland Compiler, 64bit, Win7. Short & Sweet: Im having a strncat problem. Im using ...

  1. #1
    Registered User
    Join Date
    Dec 2011
    Location
    Los Angeles, California, United States
    Posts
    5

    STRNCAT Problem

    Hi, Thanks in advanced. Specs: C, Borland Compiler, 64bit, Win7.

    Short & Sweet:
    Im having a strncat problem. Im using a loop to iterate through input and strncat to write two different strings based on the input. The problem is that the new strings will have some of the other characters in them.

    Code:
    gets(string);
    
    for( i=0; i < (int)strlen(string); ++i )
    {
         //if the input is a number, write it to a string named num.
         if( string[i] >= 47 && string[i] <= 58)
              strncat(num, &string[i], 1);
    
        //if the input is a character, write it to a string named alpha. 
         else
              strncat(alpha, &string[i], 1);
    }
    
    puts(num);
    puts(alpha);

  2. #2
    Registered User
    Join Date
    Sep 2011
    Posts
    111
    What exactly are you trying to do, and what is the problem you are having?

    Syntax:

    #include <string.h>
    char *strncat( char *str1, const char *str2, size_t count );


    Description:
    The function strncat() concatenates at most count characters of str2 onto str1, adding a null termination. The resulting string is returned.
    Maybe strcat() is what you want to do?

    Syntax:

    #include <string.h>
    char *strcat( char *str1, const char *str2 );

    Description:
    The strcat() function concatenates str2 onto the end of str1, and returns str1.

  3. #3
    Registered User
    Join Date
    Dec 2011
    Location
    Los Angeles, California, United States
    Posts
    5

    re:

    Im trying to produce two strings from one. The first containing all of the numbers and the second with all of the other characters.
    ex.
    string[123abc] --> s1[123] & s2[abc];

    The problem is that the piece of code above puts some numbers in with the letters and some letters in with the numbers.
    ex.
    string[123abc] --> s1[123abc] & s2[23abc]

    The actual piece of code. The problem ex. is input/output take directly from this code.
    Code:
    void loop(char *string)
    {
        int i;
        int nLength = strlen(string);
        char *num = "";
        char *alpha = "";
        
        for(i=0; i < nLength; ++i)
        {    
            if( string[i] >= 47 && string[i] <= 58 )
            {
                printf("%c\n", string[i]);
                strncat(num, &string[i], 1);
            }
            else 
            {
                printf("%c\n", string[i]);
                strncat(alpha, &string[i], 1);
            }
        }
        puts(num);
        puts(alpha);
    }
    Last edited by ogginger; 12-11-2011 at 08:59 PM. Reason: added actual code

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Is there a fixed format... say 3 numbers then 4 letters ... or is it different every time?

    Can you give us a sample of some of the strings you're trying to burst?

    You might also want to look into using isdigit() and isalpha() for sorting.

    And ... you really shouldn't use gets() as it will easily allow you to overrun the limits of your input buffer. Use fgets() instead.... as ... fgets(buffer, size, stdin); ... no more overruns.

  5. #5
    Registered User
    Join Date
    Dec 2011
    Location
    Los Angeles, California, United States
    Posts
    5
    No fixed format. The input should be able to vary: "1" or "abc" or "123abc...".
    Code:
    Here are some samples:
    1.INPUT:123   
    num:123    
    alpha:23
    
    2.INPUT:abc              
     num:                           
    alpha:abc       
    
    3.INPUT:123abc  
    num:123abc
    alpha:23abc
    
    4.INPUT:abc123
    num: bcbc123
    alpha: 23
    Out of the samples, #2 was the only success.


    __________________________________________________ ___________________
    I want to modify the code for other conditions to trigger the sorting. It's specifically a problem with strncat and the output. The code above seemed like the easiest way to communicate the problem I was having.
    Last edited by ogginger; 12-11-2011 at 10:17 PM.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Phooey!

    This is dead simple if you just write your own code for it. You have one hour to do so:

    << CLOCK IS TICKING! >>


  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    Don't use magic numbers like 47 and 58. If it's supposed to be between '0' and '9' then just use '0' and '9' (including those single quotes).

    This line is the same in the if and the else:
    Code:
                printf("%c\n", string[i]);
    Instead of duplicating it for both the if and the else, just do it before the if.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    Registered User
    Join Date
    Dec 2011
    Location
    Los Angeles, California, United States
    Posts
    5
    I changed the code to:
    Code:
    void loop(char *string)
    {
        int i;
        int nLength = strlen(string);
        char *num = "\n";
        char *alpha = "\n";
        
        for(i=0; i < nLength; ++i)
        {    
            printf("%c\n", string[i]);
            if( string[i] >= '0' && string[i] <= '9' )
            {
                
                strncat(num, &string[i], 1);
            }
            else
            
            {
                strncat(alpha, &string[i], 1);
            }
        }
        puts(num);
        puts(alpha);
    }
    
    The new code samples:
    
    1.INPUT:ABC OUTPUT: a b abc ------------- 2.INPUT:123 OUTPUT: 1 2 3 123 23 -------------
    I don't know if that gives you more insight but it seems to be more buggy.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Time's up!

    Code:
    #include <stdio.h> 
    #include <string.h>
    #include <ctype.h>
    
    #define ROWS 4
    #define SIZE 24
    
    int main() { //  string work
       int row=0,i,j,k,len,test=0;
       char input[ROWS][SIZE]={{"123"},{"abc"},{"123abc"},{"abc123"}};
       int num[SIZE]={0};
       char alpha[SIZE]={'\0'};
    
    
       for(row=0;row<ROWS;row++) {
          printf("Input: %s\t\t",input[row]);
          len=strlen(input[row]);
          
          j=k=0;
          for(i=0;i<len;i++) {
             test = input[row][i]; 
             if(isdigit(test)) {
                num[j++]=test-'0';
             }else {
                alpha[k++]=input[row][i];
             }
          }
          
          printf("alpha: ");   
          for(i=0;i<k;i++) 
             printf("%c",alpha[i]);
          if(k<j)
             for(;k<j;k++)
                putchar(' ');
    
          printf("\t\tnum: ");
          for(i=0;i<j;i++)
             printf(" %d ", num[i]);
          printf("\n\n"); 
    
       } 
       printf("\n");
       return 0;
    }
    Give that a study.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Give this a try....

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    void split(char *num, char *alpha, char *string)
      { 
         int len = strlen(string);
         int i;
         char *n = num;
         char *a = alpha;
    
         for(i = 0; i < len; i++)
           {
             if (isalpha(string[i]))
               *(a++) = string[i];
             else if (isdigit(string[i]))
               *(n++) = string[i];
            }
           *n = 0; 
           *a = 0;
       } 
    
    
    
    int main (void)
      {
         char *test1 = "abc123";
         char *test2 = "456efg";
         char num[10];
         char alpha[10];
    
         split(num,alpha,test1);
         printf("abc123 = %s and %s\n",num, alpha);
    
         split(num,alpha,test2);
         printf("abc123 = %s and %s\n\n",num, alpha);
    
         return 0;
    }

  11. #11
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,546
    > char *num = "\n";
    > char *alpha = "\n";
    On any decent OS/Compiler, any attempt to modify these string constants would have instantly resulted in the untimely demise of your program (via a segfault).

    The other big issue you had was that strncat always LOOKS for a \0, but doesn't always ADD a \0.
    So you need to do something else (as well) if you want to generalise the "append char to string" function.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    Registered User
    Join Date
    Dec 2011
    Location
    Los Angeles, California, United States
    Posts
    5
    Okay got it. Thank you guys so much!!! I really appreciate the advice. I got a bunch of general tips for improving my coding and ultimately the pointer use in commontater's split function helped me figure out my problem.

    Sincerely,
    og.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with strncat command
    By learning_grc in forum C Programming
    Replies: 9
    Last Post: 10-14-2011, 12:19 AM
  2. alternative to strcat/strncat
    By DampfHans in forum C Programming
    Replies: 4
    Last Post: 12-02-2010, 10:28 AM
  3. Problems with strncat
    By CashCow01 in forum C Programming
    Replies: 8
    Last Post: 03-11-2010, 07:44 AM
  4. Pointers and strncat
    By simpatico_qa in forum C Programming
    Replies: 14
    Last Post: 04-27-2009, 02:35 AM
  5. Problem with strncat() function (newbie)
    By Kettch in forum C Programming
    Replies: 2
    Last Post: 12-08-2001, 01:54 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21