Jay*_*son 3 c formatting user-input
显然,C 语言中没有标准化的方法来居中对齐文本,所以我
我想知道如何编写 if 语句来居中对齐接下来的 N 行
的文本。例如,如果程序.ce2在文本文件中找到它应该
在页面中央打印接下来的两行,然后照常进行。
.ce2 This is my heading
Lesson 1
Task 2
Run Code Online (Sandbox Code Playgroud)
输出:
This is my heading
Lesson 1
Run Code Online (Sandbox Code Playgroud)
Task 2
下面是我编写的代码,我实现了.br打破的功能
句子以及.sp在文本中添加空白行的功能。
int main(void) {
FILE *fp = NULL;
char file_name[257] = {'\0'};
char line[61] = {'\0'};
char word[61] = {'\0'};
int out = 0;
int blanks;
int space;
printf ( "Enter file name:\n");
scanf ( " %256[^\n]", file_name);
if ( ( fp = fopen ( file_name, "r")) == NULL) {
printf ( "could not open file\n");
return 1;
}
while ( ( fscanf ( fp, "%60s", word)) == 1) { //breaks the sentence after .br
if ( strcmp ( word, ".br") == 0) {
printf ( "%s\n", line);
line[0] = '\0';
out = 1;
}
if ( strncmp ( word, ".sp", 3) == 0) { // creates n amount of spaces after .sp
if ( ( sscanf ( &word[3], "%d", &blanks)) == 1) {
printf ( "%s\n", line);
while ( blanks) {
blanks--;
printf ( "\n");
}
line[0] = '\0';
out = 1;
}
if ( strncmp ( word, ".ce", 3) == 0) { // centre the next n lines
if ( ( sscanf ( &word[3], "%d", &space)) == 1) {
//this is the if statement I am stuck at on what to include
}
line[0] = '\0';
out = 1;
}
Run Code Online (Sandbox Code Playgroud)
printf不提供居中文本的机制,但它确实提供了右对齐文本(字段宽度)的机制以及将字段宽度指定为参数的机制。将这两者放在一起,很容易将文本居中:
int print_centered(FILE* f, const char* str, int width) {
int len = strlen(str);
if (len < width)
return fprintf(f, "%*s\n", (width + len) / 2, str);
else /* Line is too long to fit */
return fprintf(f, "%s\n", str);
}
Run Code Online (Sandbox Code Playgroud)
如果您想截断太长而无法容纳的行,可以使用“精度”,在%s格式的情况下,它会限制要打印的字符串的长度:
int print_centered_or_truncated(FILE* f, const char* str, int width) {
int len = strlen(str);
if (len < width)
return fprintf(f, "%*s\n", (width + len) / 2, str);
else /* Line is too long to fit */
return fprintf(f, "%.*s\n", width, str);
}
Run Code Online (Sandbox Code Playgroud)
请参阅man fprintf了解更多详情。