一道C++的题,非常急!!!在线等!!!!!答后追加高分!!!!!

Write a program that reads names (from an input file) in the following format (you can assume names are no more than 30 characters if you are using C-string):

First_name Middle_name/Middle_initial Last_name

The program then outputs (to a file) the name in the following format (a period must be place right after the Middle_initial. The first character of First/Middle/Last name must be capitalized):

Last_name, First_name Middle_initial.

The input file name must be "infile" and the output file name must be "outfile". There are unknown number of persons in input files, however, each person's name occupies a line. And each person must have First, Middle/Middle Initial, and Last in the format described above.

Example:
Suppose the input file consists of (special consideration is required for the case "Mary J. Horn"):
Mary J. Horn
John Jerry Doe
Edward David Cain

Then the output file should contain:
Horn, Mary J.
Doe, John J.
Cain, Edward D.

既然是C++,最好把readLine这个封装到类里面,我图省事写成全局的了。

#include <iostream>
using namespace std;
int readLine(FILE *fp, char **buf, int *bufsize)
{
char * newbuf = 0;
int offset = 0;
int len = 0;

if(*buf == 0)
{
*buf = new char[128];
if(!*buf)
{
return -2;
}
*bufsize = 128;
}

while(1)
{
if(!fgets(*buf + offset, *bufsize - offset, fp))
{
return (offset != 0) ? 0 : (ferror(fp)) ? -2 : -1;
}
len = offset + (int)(strlen(*buf + offset));
if((*buf)[len - 1] == '\n')
{
(*buf)[len - 1] = 0;
return 0;
}
offset = len;

newbuf = new char[*bufsize * 2];
if (!newbuf)
{
return -2;
}
strcpy(newbuf, *buf);
delete[] *buf;
*buf = newbuf;
newbuf = 0;
*bufsize *= 2;
}
return 0;
}

int main()
{
FILE * infile = fopen("infile", "r");
if (infile == 0)
{
cout << "Open the infile failed!" << endl;
return -1;
}

FILE * outFile = fopen("outfile", "w");
if (outFile == 0)
{
cout << "Create the outFile failed!" << endl;
return -1;
}

char *line = 0;
int lineSize = 0;

while (readLine(infile, &line, &lineSize) == 0)
{
string strLine = line;
int firstSpacePos = strLine.find(" ", 0);
int secondSpacePos = strLine.find(" ", firstSpacePos + 1);

string firstName = strLine.substr(0, firstSpacePos);
string middle = strLine.substr(firstSpacePos + 1, secondSpacePos - firstSpacePos - 1);
string lastName = strLine.substr(secondSpacePos + 1, strLine.size() - secondSpacePos - 1);

string outLine = lastName;
outLine += ",";
outLine += firstName;
outLine += " ";
outLine += middle;
outLine += "\n";
fwrite(outLine.c_str(), sizeof(char), outLine.size(), outFile);
}
delete[] line;
fclose(infile);
fclose(outFile);
return 0;
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答