我正在尝试为每个空格添加一个空格,直到column = 0
。我不知道该怎么做。
问题如下。如果你看报纸,你会发现文章的内容很适合专栏。写一个程序
它读取报纸中栏的宽度,然后读取一行文本。对齐文本行以适应
该宽度的列。当你的程序运行时,屏幕应该看起来像这样:
Enter the width of the column: 40
Enter a line of text: Good morning how are you?
12345678901234567890123456789012345678901234567890...
Good morning how are you?
论证是通过计算文本中的间隙数量来完成的。在上面的例子中,有 4 个间隙。然后每个间隙都必须添加空格。额外空间的数量必须尽可能均匀地分配。在上面的示例中,前三个间隙各有 5 个空格,最后一个间隙有 4 个空格。
Notes:
- 如果文本比列长,那么您必须报告错误 - 不要尝试将其分成两行!
- 假设文本中包含多个单词。
- 请注意标题行由 123456789012345678.... 组成,这对于检查结果很有用。
您可以根据需要将此标题行设置为任意长度 – 70 个空格是有用的长度。
Thanks
#include <stdio.h>
int clear_input_buffer(void);
int column;
int c;
int g;
int e;
int space;
int length;
char line[40];
int main(){
g = 0;
printf("enter width of column\n");
scanf("%d", &column);
printf("enter line of text\n");
clear_input_buffer();
gets(line);
c = 0;
while(c <= column){
if(g <= 9)
{
printf("%d", g);
g = g + 1;
c = c + 1;
}
else
{
g = 0;
printf("%d", g);
g = g + 1;
c = c + 1;
}
}
printf("\n%s", line);
space = 0;
length = 0;
for( e = 0; line[e] != '\0'; e++ )
{
length = length + 1;
if( line[e] == ' ' )
space = space + 1;
}
column = column - length;
for( e = 0; line[e] != '\0'; e++ )
{
if((line[e] == ' ') && (column > 0))
{
add space to here
column = column - 1;
}
}
printf("%d\n", space);
printf("%d", length);
printf("%s", line);
}
int clear_input_buffer(void) {
int ch;
while (((ch = getchar()) != EOF) && (ch != '\n')) /* void */;
return ch;
}
这就是我做的。这远非理想,但你明白了。
您只需输入条件(例如当输入的字符串大于或等于 40 个字符时)即可跳过该过程。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
int i = 0; // first just initialiaze stuff
char ch[40]; // memset the arrays, get the string
memset(ch, '\0', 40);
gets(ch);
int diff = 40 - strlen(ch);
int spaces = 0;
while(i<strlen(ch))
{
if(*(ch + i++) == ' ') // count the number of words/spaces between words
spaces++;
}
char finalt[40];
memset(finalt, '\0', 40);
i = 0;
diff /= spaces; // diff is the number of spaces to be added between every word
i = 0;
int j = 0; // j is for the finalt array
int k = 0; // k counts through the while, to put in spaces
printf("%d\n", diff);
while(i<40) // just squeeze in the spaces
{
if(ch[i] == ' ') {while(k<diff){ finalt[j++] = ' '; k++;} k = 0;}
else {finalt[j] = ch[i]; j++;}
i++;
}
printf("%s\n", finalt); // print the result
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)