我的任务是编写一个程序,读取以句点结尾的句子并将第一个字母大写并将每个句子输出到一个文件(出于测试目的,我的代码输出到控制台)。我编写的程序完全有效,它完成了它应该做的事情,唯一的问题是它读取所有行之后会进行额外的运行并输出空格。请帮我弄清楚是什么原因造成的。
#include <iostream>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
int main()
{
const int MAX_NUM=51;
ifstream infile;
ofstream outfile;
char fileName[MAX_NUM];
char ch,ch2;
//prompt for file name
cout << "Enter an input file name: " ;
cin.getline(fileName,MAX_NUM);
infile.open(fileName,ios::in); //open input file
if(!infile)
{
cout<<"Error: "<<fileName<<" could not be opened.\n";
return 0;
}
cout << "Enter an output file name: " ;
cin.getline(fileName,MAX_NUM);
outfile.open(fileName,ios::out); //open output file
if(!outfile)
{
cout<<"Error: "<<fileName<<" could not be opened.\n";
return 0;
}
while(infile.get(ch))
{
ch2=toupper(ch);
cout<<ch2;
while (infile.get(ch) && ch!='.')
{
ch2=tolower(ch);
cout<<ch2;
}
cout<<'.'<<endl;
}
//close files
infile.close();
outfile.close();
return 0;
}