Thread: justifying text

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    4

    justifying text

    do u have any idea about justifying text in C. I need help! F1! F1!
    Rules :
    1. Each line should start and end with an alphanumeric letter unless there is only one word in the line.
    2. Each line length should be equal to the user specified length.
    3. A word shouldn’t be broken into two parts.
    4. The white space should be distributed in a balanced way.

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    void main() {
    	
    	char sstr[] = "  ModelSim provides an Integrated Debug"
    "Environment that facilitates efficient design debug for SoC and"
    "FPGA based designs. This GUI has continuously evolved to"
    "include new windows and support for new languages. This"
    "application note aims to give an introduction to the ModelSim"
    "6.0 debug environment. This environment is trilingual"
    "supporting designs based on VHDL, Verilog (all standards"
    "including SystemVerilog, Verilog 2001 and Verilog 1995),"
    "and SystemC. Subsequent releases of ModelSim will enable"
    "even more debug capabilities supporting higher levels of"
    "abstractions for verification and modeling in SystemVerilog and"
    "SystemC. In ModelSim 6.0, the GUI has been enhanced and is"
    "based on Multiple Document Interface (MDI) layout standard. In"
    "addition, the debug windows have been re-organized in such a"
    "way as to display design data and simulation results in an"
    "intuitive manner.";
    	
    	int twid; 
    	int slen = 0;
    
        slen = strlen(sstr); // Length of the input string
    	//printf("\nlen :%d\n", slen);
    
        printf("Enter text width :");
    	scanf("%d",&twid);
        //printf("\nText Width %d",twid);
    
        
    
    }
    What can I do? Examples of outputs exist in attachments.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    main() returns int.

    What you should do is count how many spaces are required to stretch the text to 80 chars wide (or whatever your width is), and count the number of spaces in a line. Then you can print a few spaces instead of each space.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,212
    Code:
    char *s = "right justified";
    printf("%80s", s);

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    That's not what the OP is trying to do. They're trying to re-format text (like man) so that it stretches across a line. (That's what I thought at first, too, though.)
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    1 - Create a buffer called 'line'.
    2 - strncpy 'width' characters into it.
    3 - If the last character is not a space, back track, incrementing a counter, until you hit a space.
    4 - The counter is the number of spaces you need to insert.
    5 - Insert them throughout the string by moving 'line's contents around.
    6 - Eat.
    7 - Drink.
    8 - Be merry.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    4
    Does anyone have any example?

  7. #7
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Quote Originally Posted by a.baki
    Does anyone have any example?
    Translation: "Can anyone write it for me?"

    ...and yes that's what that means. Any example we can provide might as well be your entire program. Quzah gave a good idea of what to do. He even gave you functions for the first few steps. You can compare the current character to a space easily with your comparison operator
    Code:
    line[width - counter] == ' '
    // or if you wish isspace(line[width - counter]) from cctype
    Sent from my iPad®

  8. #8
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    We can teach you, but you'll have to do it yourself. Read
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    How about practicing on half of the problem
    Code:
    void formatLine ( char *line, int width ) {
      // work out the current length of the line - strlen perhaps
      // work out how many spaces it contains
      // work out how many extra spaces to add
      // print the line, printing the appropriate number of extra spaces
    }
    
    int main ( ) {
      formatLine ( "this is a test", 40 );
      formatLine ( "I wonder how this line will look", 40 );
      formatLine ( "this line is exactly 40 characters long!", 40 );
      return 0;
    }
    When you've got that working, then work out how to extract a series of sub-strings from your long string.

    When you've done that, join both programs together.
    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.

  10. #10
    Registered User
    Join Date
    Apr 2006
    Posts
    4

    ...

    I try something. But with small width there is something wrong, I cannot stop while loop. There is any other way to control my while loop?

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    void justifytext ( char *mytext, int width);
    void justifyline ( char *line, int linewidth );
    
    void main() {
    	
    	char sstr[] = "  ModelSim provides an Integrated Debug "
    		"Environment that facilitates efficient design debug "
    		"for SoC and FPGA based designs. This GUI has continuously "
    		"evolved to include new windows and support for new languages. "
    		"This application note aims to give an introduction to the "
    		"ModelSim 6.0 debug environment. This environment is "
    		"trilingual supporting designs based on VHDL, Verilog "
    		"(all standards including SystemVerilog, Verilog 2001 "
    		"and Verilog 1995), and SystemC. Subsequent releases of"
    		" ModelSim will enable even more debug capabilities "
    		"supporting higher levels of abstractions for verification"
    		" and modeling in SystemVerilog and SystemC. In ModelSim"
    		" 6.0, the GUI has been enhanced and is based on Multiple"
    		" Document Interface (MDI) layout standard. In addition, "
    		"the debug windows have been re-organized in such a way as"
    		" to display design data and simulation results in an intuitive manner.";
    
    int twid; 
    	int slen = 0;
    	
        slen = strlen(sstr); // Length of the input string
    	
    	printf("\nLength of your text : %d\n", slen);
    
        printf("Enter text width :");
    	scanf("%d",&twid);
        printf("\nText Width %d\n",twid);
    
    	justifytext ( sstr, twid );
    	
    	printf ("\n\n");
    }
    
    void justifytext ( char *mytext, int width){
    	
    	char temp[100];//a string array for calling my second function
    	int i,j, currenti, counter = 0;
    
    	for ( i = 0; isspace(mytext[i]); i++ );        //if there is any space at the 
    	memmove ( mytext, &mytext[i], strlen(mytext) );//beginning of the text, DELETED.
    	
    	i = 0;	
    	while (  counter < (int)strlen(mytext) ){//I choose such a control-loop, because I try
    											 //some other ways and this is most trustable.
    		
    		for ( i, j = 0; j < width; i++, j++ ){//finding each parts of text to justify
    			temp[j] = mytext[i];
    		}		
    	
    		for ( i ; !(isspace(mytext[i])); i--, j-- );//I cannot sperate any word, 
    		                                            //looking for spaces
    		currenti = i;                               //I will use it to start the next line
    	
    		for ( i; isspace(mytext[i]); i--, j-- );//This makes part of array suitable 
    		                                        //for my second function.
    		counter = i; //for controlling loop     //my second function works for only 
    		                                        //strings that do not have spaces
    											    //neither at the begining nor at the end.
    
    		for ( ++j ; j < 100; j++ ) // only temp[++j] = '\0' is enough without for loop
    			temp[j] = '\0';        // but this makes me relax
    
    		justifyline ( temp, width );
    
    		i = currenti + 1;    // this is where I start to sperate next time
    		
    	}
    }
    
    void justifyline ( char *line, int linewidth )
    {
    	char *temp;   // it for usage of strtok function
    	int i, j, spaces = 0, spacestoshare=0, equalshare=0, extras=0;
    
    	for ( i = 0; line[i] != '\0'; i++ ){  //counting spaces. Also this means likely 
    		                                  //how many words there
    
    		if ( isspace ( line[i] ) ){
    			spaces++;
    		}
    	}
    
    	spacestoshare = linewidth - strlen(line); 
    
    	if ( spaces == 0 ){
    		equalshare = spacestoshare+spaces; //if spaces zero, there is only a word means
    		extras = 0;                        // I put all my spaces after the word. No extras
    	}
    
    	else {
    		equalshare = (spacestoshare+spaces)/spaces;//How many spaces I will put between 
    		                                           //each word in equal
    		extras = spacestoshare % spaces;           //Extra spaces to put
    	}
    	
    	for ( temp = strtok ( line, " " ); temp != NULL; temp = strtok ( NULL, " ") ){ //takes 
    		                                                             //each word sperately
    
    		printf ("%s", temp); //first write one word
    
    		for ( j = 0; j < equalshare; j++ ) { // add spaces after the word
    			putchar (' ');
    		}
    		
    		if ( extras != 0 ){ // if there is extra 
    			putchar (' ');  //also add them
    			extras --;
    		}
    	
    	}
    	putchar ('\n');	
    }

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    for ( i ; !(isspace(mytext[i])); i--, j-- )
    The initialization part of a for loop (or any part of a for loop, for that matter) can be empty. You don't need to put just i in.

    Code:
    for ( i, j = 0; j < width; i++, j++ ){
    Perhaps you want to initialize j to counter?

    Otherwise you will indeed have an infinite loop.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 02:59 PM
  2. struct question
    By caduardo21 in forum Windows Programming
    Replies: 5
    Last Post: 01-31-2005, 04:49 PM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM