好久没有更新了,最近在疫情期间裸辞,还疯狂的“游戏”了一个月的人生,现在把心收回来,继续写博客。
此案例为文本格式化的程序justify,文案摘自《C语言程序设计现代方法》
word.h。c++调用c需要加 extern “C”
#ifndef WORD_H
#define WORD_H
#ifdef __cplusplus
extern "C" {
#endif
void read_word(char* word, int len);
#ifdef __cplusplus
}
#endif
#endif
word.c
#include "word.h"
#include <stdio.h>
int read_char(void) {
int ch = getchar();
if (ch == '\n' || ch == '\t')
return ' ';
return ch;
}
void read_word(char* word, int len) {
int ch = 0, pos = 0;
while ((ch == read_char()) == ' ')
;
while (ch != ' ' && ch != EOF) {
if (pos < len) {
word[pos++] = ch;
}
ch = read_char();
}
word[pos] = '\0';
}
line.h
#ifndef LINE_H
#define LINE_H
extern "C" {
void clear_line(void);
void add_word(const char* word);
int space_remaining(void);
void write_line(void);
void flush_line(void);
}
#endif
line.cpp
#include "line.h"
#include <stdio.h>
#include <string.h>
#define MAX_LINE_LEN 60
char line[MAX_LINE_LEN + 1];
int line_len = 0;
int num_words = 0;
void clear_line(void) {
line[0] = '\0';
line_len = 0;
num_words = 0;
}
void add_word(const char* word) {
if (num_words > 0) {
line[line_len] = ' ';
line[line_len + 1] = '\0';
line_len++;
}
strcat_s(line, word);
line_len += strlen(word);
num_words++;
}
int space_remaining(void) {
return MAX_LINE_LEN - line_len;
}
void write_line(void) {
int extra_spaces, spaces_to_insert, i, j;
extra_spaces = MAX_LINE_LEN - line_len;
for (i = 0; i < line_len; i++) {
if (line[i] != ' ')
putchar(line[i]);
else {
spaces_to_insert = extra_spaces / (num_words - 1);
for (j = 1; j < extra_spaces + 1; j++)
putchar(' ');
extra_spaces -= spaces_to_insert;
num_words--;
}
}
putchar('\n');
}
void flush_line(void) {
if (line_len > 0)
puts(line);
}
justify.c
#include <iostream>
#include <string.h>
extern "C" {
#include "line.h"
#include "word.h"
}
#define MAX_WORD_LEN 20
int main()
{
char word[MAX_WORD_LEN + 2];
int word_len;
clear_line();
for (;;) {
read_word(word, MAX_WORD_LEN + 1);
word_len = strlen(word);
if (word_len == 0) {
flush_line();
return 0;
}
if (word_len > MAX_WORD_LEN)
word[MAX_WORD_LEN] = '*';
if (word_len + 1 > space_remaining()) {
write_line();
clear_line();
}
add_word(word);
}
}
makefile
justify: justify.o word.o line.o
gcc -o justify justify.o word.o line.o
justify.o: justify.c word.h line.h
gcc -c justify.c
word.o: word.c word.h
gcc -c word.c
line.o: line.c line.h
gcc -c line.c
或者
gcc -o justify justify.c line.c word.c