题目:
If you look at a newspaper you will see that the writing is justified (spread out) to fit into the columns. Write a program that reads in two lines of text and justifies the lines to fit into a column width of 50. Your program should include three functions:
- readline that reads in a line of text of not more than 50 characters, and returns its length
- countgaps that counts and returns the number of gaps between words in a line of text
- display that prints out a justified version of a line of text
When your program is running, the screen should look something like this:
Enter first line of text: Good morning how are you?
Enter second line of text: I’m good thanks, and how are you?
12345678901234567890123456789012345678901234567890
Good morning how are you?
I’m good thanks, and how are you?
The justification is done by counting the number of gaps in the text. In the above examples, there are 4 and 6 gaps respectively in the two lines. Then each gap must have an equal share of spaces added to it with any left over spaces being distributed one per gap until they run out. In the first line of the example, the first gap has 8 spaces and the other three gaps have 7 spaces each. In the second line of the example, the first five gaps have 4 spaces each and the last gap has 3 spaces.
Notes:
1. If the text is longer than the column you must report an error – don't try and break it into two lines!
2. Assume that the lines of text will have more than one word in them.
3. Assume that all gaps are always typed in with only one space.
4. Do not store the justified strings. Simply display one character at a time in the justified format.
5. Note the header line consisting of 123456789012345678.... This is useful to check your result.
我自己写了一半, display 部分完全没有头绪。。。哪位大神能帮帮我!~#include<stdio.h>
#include<string.h>
int readline(char sentence[1024]);
int countgaps(char sentence[1024],int length);
int length1;
int length2;
int gap1;
int gap2;
int main(){
char sentence1[1024];
char sentence2[1024];
while(1){
printf("Enter first line of text:");
gets(sentence1);
length1=readline(sentence1);
if(length1!=-1){
break;}
}
while(1){
printf("Enter second line of text:");
gets(sentence2);
length2=readline(sentence2);
if(length2!=-1){
break;}
}
printf("%d,%d,",length1,length2);
gap1=countgaps(sentence1,length1);
gap2=countgaps(sentence2,length2);
printf("%d,%d",gap1,gap2);
}
int readline( char sentence[1024]){
int len;
len=strlen(sentence);
if(len>50){
printf("Error! The text is longer than the column,");
len=-1;
} else{
len=strlen(sentence);
}
return len;
}
int countgaps(char sentence[1024],int length){
int gaps;
int i;
gaps=0;
for(i=0;i<length;i++){
if(sentence[i]==' '){
gaps++;
}
}
return gaps;
}
|