我在此程序上遇到了一些麻烦,我无法弄清楚自己在做什么错;该程序仍然不允许显示文件,并且仍然不会将字母“ a”大写。应该从外部文件input.txt中读取该程序,将所有以字母“ a”开头的单词都大写,然后将其写入外部文件output.txt中。任何帮助将不胜感激!谢谢!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void nm(string nm, ifstream& xfile);
void mov(ifstream& xfile, string& valfile);
void exam(string& valfile);
void display(string nm, ofstream& yfile, string& valfile);
int main()
{
ifstream xfile;
ofstream yfile;
string valfile;
nm("input.txt", xfile);
mov(xfile, valfile);
exam(valfile);
display("output.txt", yfile, valfile);
}
void nm(string nm, ifstream& xfile)
{
xfile.open(nm);
if (xfile.fail())
{
cerr << "Unable to open file \"" << nm << "\" for reading.\n";
exit(1);
}
}
void mov(ifstream& xcode, string& valfile)
{
while (xcode.good())
{
valfile += xcode.get();
}
xcode.close();
cout << endl << '[' << valfile[valfile.length()-1] << ']' << endl;
valfile = valfile.substr( 0, valfile.length()-1 );
}
void exam(string& valfile)
{
for(int i = 1; i < valfile.length(); i++)
{
if( valfile[i] == 'a' && isspace((int) valfile[i-1]) &&
( isspace((int) valfile[i+1]) || isalpha((int) valfile[i+1]) ) )
{
valfile[i] = 'A';
}
}
}
void display(string nm, ofstream& yfile, string& valfile)
{
yfile.open(nm);
yfile << valfile;
yfile.close();
}
为了在gcc编译器上编译您的代码,我必须进行以下修改:
#include <cstdlib>
为exit
要定义的功能添加了
换行:
xfile.open(nm);
成xfile.open(nm.c_str());
yfile.open(nm);
成yfile.open(nm.c_str());
因为nm是一个字符串,并且ifstream / ofstream.open采用普通的旧字符数组。要将字符串转换为char数组,请使用somestring.c_str()
function。
此表达式valfile[valfile.length()-1]
将返回valfile字符串中的最后一个字符……例如,如果file不为空,则valfile [0]将从文件中仅返回一个(第一个)字符。要纠正它,只需打印出valfile
:
cout << endl << '[' << valfile << ']' << endl;
在您的考试功能中添加这个丑陋的技巧,以a
在文件开头大写可能的字符:
void exam(string& valfile)
{
if( (valfile.length()>=1) && (valfile[0]=='a')) valfile[0]='A';
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句