这是一个 C 作业。我不是要求任何人为我做这件事,我只是碰壁了。明天就要交了,不知道怎么办。我是初学者,我的头开始受伤
编写一个 ANSI C 程序,该程序对文本进行格式化,以便它很好地适合给定数量的列。文本格式化程序必须右对齐输入文本文件,以便右边距对齐在一条直线上,但有一个例外。最后一行没有正确对齐。此外,段落不会合并在一起。输出线之间的间距应均匀分布。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define IN 1
#define OUT 0
/*
This is the start of the main pgoram which originated from the K & R word counter...
we comment to understand each part...
*/
int main()
{
/*
* This is the pointer to the file object we will be readin in
* from...
*/
FILE *ptr_file;
char *outputbuf;
/*
* This variable will hold the maximum width of the line we are to
* output
*/
int width;
char eatspace;
char c; /* We read each character invidually */
int state = OUT;
int nc = 0; /* This is the total count of all words in the document */
int nl = 0; /* This is the total count of newlines in the document */
int nw = 0;
int lw = 0; /* Count the total whitespaces spaces per line */
int buff_offset = 0; /* Keep track of how many letters we are into the current output line */
/* Opens a file stream for the .txt file to be read in */
ptr_file = fopen("hollo_man.txt", "r");
if ((fopen("hollo_man.txt", "r")) != NULL) {
/*
* This loop reads in one character at a time until the end
* of file
*/
/* Read the first line to get the width of the output */
fscanf (ptr_file, "%i", &width);
outputbuf = (char*) malloc(width + 1);
//fscanf(ptr_file, "%c", &eatspace);
int prev_char_was_space = 0;
while ((c = fgetc(ptr_file)) != EOF)
{
++nc;
if (c == '\n' || strlen(outputbuf) == width)
{
outputbuf[buff_offset] = '\0';
++nl;
// printf("Saw a newline, newline count is now: %i\n", nl);
/* Our buffer needs to be ended since we saw a newline */
for(int i = 0; i < (width - buff_offset); i++)
{
printf(" ");
}
printf("%s\n", outputbuf);
memset(outputbuf, width, '\0');
buff_offset = 0;
prev_char_was_space = 0;
}
/* This more verbose check is to see if there is other whitespace */
else if (isspace(c))
{
/* We only store one space between words in the output, this allows us to easily and evenly pad with white space later */
if (!prev_char_was_space)
{
outputbuf[buff_offset] = c;
outputbuf[buff_offset + 1] = '\0';
buff_offset++;
lw++;
prev_char_was_space = 1;
}
}
else /* This was not a whitespace character so store it in the current line buffer */
{
prev_char_was_space = 0; /* Keep track that we didnt have a whitespace for the next iteration */
outputbuf[buff_offset] = c;
buff_offset++;
++nw;
}
} /* End reading each character */
/* This line should indeed print output to console for now */
//fprintf(stderr, "ORIG LINE COUNT: %d\nORIG WORD COUNT: %d\nORIG CHAR COUNT: %d\n", nl, lw, nc);
/* Close our file and clean up */
fclose(ptr_file);
}
return 0;
}
它所做的只是打印出一个空白行。我想我需要另一个缓冲区,但我真的不知道。我将如何打印它,然后用填充空格均匀地间隔单词?我也不确定如何将每一行打印到指定的宽度。任何帮助将不胜感激!