我在使用这个程序时遇到了一些问题,我不知道自己做错了什么;该程序仍然不允许显示文件,它仍然不会将字母“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 采用普通的旧字符数组。要将字符串转换为字符数组,您可以使用
somestring.c_str()
功能。这个表达式
valfile[valfile.length()-1]
将返回 valfile 字符串中的最后一个字符...例如,如果文件不为空,valfile[0] 将只返回文件中的一个(第一个)字符。要更正它,只需打印出valfile
:cout << endl << '[' << valfile << ']' << endl;
将这个丑陋的 hack 添加到您的考试功能中以利用可能的
a
文件开头的字符:void exam(string& valfile) { if( (valfile.length()>=1) && (valfile[0]=='a')) valfile[0]='A'; ...
关于c++ - 输入/输出文件(一个字母的大写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17887546/