Like Tree2Likes
  • 1 Post By quzah
  • 1 Post By ssharish2005

Limiting string length to output

This is a discussion on Limiting string length to output within the C Programming forums, part of the General Programming Boards category; Hi i am trying to limit the length of a string to output on console. So that only a max ...

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    53

    Limiting string length to output

    Hi i am trying to limit the length of a string to output on console. So that only a max of 78 char can be displayed on one line. If it exceeds that length the last word is not added to the line but moves to the next.

    This is my code so far.

    Code:
      char delims[] = " ";
        char *tokens;
        char stringLine[78] = "";
        char stringLine2[78] = "";
       
        char temp;
    
        tokens = strtok(inputStr, delims);
    
    
            while ((strlen(stringLine) + strlen(tokens)) <= 77 && tokens != NULL) {
                strncat(stringLine, tokens, 78);
                strncat(stringLine, " ", 78);
                tokens = strtok(NULL, delims);
            }
            printf("%s", stringLine);
    
            while ((strlen(stringLine2) + strlen(tokens)) <= 77 && tokens != NULL) {
                strncat(stringLine2, tokens, 78);
                strncat(stringLine2, " ", 78);
                tokens = strtok(NULL, delims);
            }
    
            printf("%s", stringLine2);
    This works fine unless the tokens == NULL then the program crashes.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by TonyG View Post
    This works fine unless the tokens == NULL then the program crashes.
    That's what happens when you pass strlen a NULL pointer in the while condition. You could get around that by rearranging those conditions. Also, you should use 76 instead of 77 for the max, to include the space you add and the null terminator that strncat() will add.

    Do you have to use strtok() for this, BTW?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    53
    Yeh just worked it out. Thanks for the post though.

    Do you have to use strtok() for this, BTW?
    What alternative?

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by TonyG View Post
    Yeh just worked it out. Thanks for the post though.
    What alternative?
    There are probably quite a few, eg:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define LINELEN 45
    char *data = "There is no restriction on the second parameter of strchr "
    			"so it could very well also be the NUL character. Those readers "
    			"thinking very hard about this might now point out that the strchr "
    			"function is more expensive than the strlen function since we have "
    			"two abort criteria. This is right. But in the GNU C library the "
    			"implementation of strchr is optimized in a special way so that "
    			"strchr actually is faster.";
    
    int main(void) {
    	int len = strlen(data), count = 0, i;
    	char *start, *end, *p, text[len];
    
    /* method 1: byte by byte */
    	strcpy(text, data);
    	start = text;
    	for (i = 0; i < len; i++) {
    		if ((count > LINELEN) && (text[i] == ' ')) {
    			text[i] = '\0';
    			printf("%s<--\n", start);
    			count = 0;
    			start = (&text[i])+1;
    			if (!start[0]) break;
    		} else count++;
    	}
    	if (i == len) printf("%s<--\n", start);
    
    
    /* method 2: pointers and strchr() */
    	strcpy(text, data);
    	start = p = text;
    	while ((end = strchr(p, ' '))) {
    		if (end - start >= LINELEN) {
    			end[0] = '\0';
    			printf("%s<--\n",start);
    			p = start = end+1;
    			if (!start[0]) break;
    		} else p = end+1;
    	}
    	printf("%s\n",start);
    
    	return 0;
    }
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    And another alternative

    Code:
    #define MAXLINECHAR 70
    
    int main()
    {
        char token[BUFSIZ];
        int n, count = 0;
            
        while( sscanf( data, "%[^ ]%n", token, &n ) > 0 )
        {
             count += n;
             if( count < MAXLINECHAR )
                 printf("%s ", token );
             else
             {
                 printf("\n");
                 count = 0;
             }
                 
             data += n;
             if( data[0] == '\0' )
                 break;
             ++data;
        }
        getchar();
        return 0;
    }
    ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  6. #6
    Registered User
    Join Date
    May 2011
    Posts
    53
    Quote Originally Posted by ssharish2005 View Post
    And another alternative

    Code:
    #define MAXLINECHAR 70
    
    int main()
    {
        char token[BUFSIZ];
        int n, count = 0;
            
        while( sscanf( data, "%[^ ]%n", token, &n ) > 0 )
        {
             count += n;
             if( count < MAXLINECHAR )
                 printf("%s ", token );
             else
             {
                 printf("\n");
                 count = 0;
             }
                 
             data += n;
             if( data[0] == '\0' )
                 break;
             ++data;
        }
        getchar();
        return 0;
    }
    ssharish
    Thank you for this it works a treat. One small error needed to add +1 to count when ever adding the value of n to cater for the space.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by TonyG View Post
    One small error needed to add +1 to count when ever adding the value of n to cater for the space.
    So figure it out and do it! Or you can just wait around until someone does it for you again.

    Guess what my money is going on.


    Quzah.
    claudiu likes this.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    Quote Originally Posted by TonyG View Post
    Thank you for this it works a treat. One small error needed to add +1 to count when ever adding the value of n to cater for the space.
    Well i'm not here to write the whole code for you. You better figure that out by yourself and and add more error checkings.
    TonyG likes this.
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  9. #9
    Registered User
    Join Date
    May 2011
    Posts
    53
    I agree. Was only pointing out. Not criticizing. Found another one. But if anyone looks on this later they can work that one out for themselves.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-03-2011, 03:00 AM
  2. Maximum integer length output?
    By RyanLeonard in forum C Programming
    Replies: 11
    Last Post: 10-20-2010, 02:22 PM
  3. Depending on length of name, output changes?
    By Hp7130p in forum C++ Programming
    Replies: 8
    Last Post: 04-21-2005, 08:21 PM
  4. Limiting Console Output
    By JKI in forum C++ Programming
    Replies: 2
    Last Post: 10-17-2003, 08:13 AM
  5. limiting length of users input
    By Unregistered in forum C Programming
    Replies: 5
    Last Post: 11-20-2001, 09:55 AM

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