学校留的一个小作业,在CSDN上找答案没找到,尤其是某个答案把人骗进去了,答案写个略。个人表示强烈谴责和鄙视。那我自己写个小代码放到这给大家参考一下。我的答案不是很完美,完全是套用老师给的template和处理老师的数据。
放代码
格式信函生成器
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define INPUT_LENGTH 128
#define FIELD_LENGTH 30
#define NUM_FIELDS 9
int main( int argc, char *argv[] )
{
FILE *template = NULL;
FILE *data = NULL;
char input[INPUT_LENGTH]; // a string for reading from a file
char customerData[NUM_FIELDS][FIELD_LENGTH]; // an array of strings for storing the results of a "split"
// yes, we're hard-coding file names... note that this is ***unacceptable***, unless we explicitly tell you to do it
template = fopen( "template.txt", "r" );
if ( template != NULL )
{
// read in the customers until we're done
data = fopen( "data.txt", "r" );
if ( data != NULL )
{
while ( fgets( input, INPUT_LENGTH, data ) != NULL )
{
// INSERT PARSING CODE HERE!
// You're tokenizing the line and putting the data into the customerData array ala split in Java
char *p;
int j=0;
p = strtok(input, "|");
while(p)
{
strcpy(customerData[j],p);
// printf("%s\n",customerData[j]);
j++;
p = strtok(NULL, "|");
}
// generate the output by reading and parsing the template
// instead of reading it into a buffer it just re-reads the file each time
rewind( template );
while ( fgets( input, INPUT_LENGTH, template ) != NULL )
{
// INSERT PARSING CODE HERE!
int cnt=0;
for(;input[cnt];cnt++)
{
if(input[cnt]=='$')
{
cnt++;
if(input[cnt]>='0'&&input[cnt]<='9')
printf("%s",customerData[input[cnt]-'0']);
}
else
printf("%c",input[cnt]);
}
// Process the input one character at a time looking for variables to replace with customerData
}
}
fclose( data );
}
fclose( template );
}
return EXIT_SUCCESS;
}
最后,说一说这个代码的不足。
没法解决**“$$1”**这样的问题。但是也很简单,再加个if判断就好了。我就是懒,完成作业即可。希望可以帮助到大家。
结束之前还是要再鄙视一下那个把我骗进去然后告诉我略的那个答案!
这几天总觉得哪里不对?原来是少放了俩文件。
第一个 data.txt
Public|Jane|Q|Ms.|600|Maple Street|Your Town|Iowa|12345
Penner|Fred|R|Mr.|123|that Street|Winnipeg|MB|R3T 2N2
Gardner|Mark|E|Mr.|76|The Avenue|Toronto|ON|M5W 1E6
Acton|Hilda|P|Mrs.|66|What Blvd|Winnipeg|MB|R3T 2N2
第二个 template.txt
Welcome back, $1!
We hope that you and all the members
of the $0 family are constantly
reminding your neighbours there
on $5 to shop with us.
As usual, we will ship your order to
$3 $1 $2. $0
$4 $5
$6, $7 $8