c++ - 输入/输出文件(一个字母的大写)

标签 c++ file fstream

我在使用这个程序时遇到了一些问题,我不知道自己做错了什么;该程序仍然不允许显示文件,它仍然不会将字母“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 编译器上),我必须进行以下修改:

  1. 已添加 #include <cstdlib>对于 exit待定义的函数

  2. 更改行:

    xfile.open(nm);进入xfile.open(nm.c_str()); yfile.open(nm);进入yfile.open(nm.c_str());

    因为 nm 是一个字符串,而 ifstream/ofstream.open 采用普通的旧字符数组。要将字符串转换为字符数组,您可以使用 somestring.c_str()功能。

  3. 这个表达式 valfile[valfile.length()-1]将返回 valfile 字符串中的最后一个字符...例如,如果文件不为空,valfile[0] 将只返回文件中的一个(第一个)字符。要更正它,只需打印出 valfile :

    cout << endl << '[' << valfile << ']' << endl;
    
  4. 将这个丑陋的 hack 添加到您的考试功能中以利用可能的 a文件开头的字符:

    void exam(string& valfile)
    {
        if( (valfile.length()>=1) && (valfile[0]=='a')) valfile[0]='A';
        ...
    

关于c++ - 输入/输出文件(一个字母的大写),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17887546/

相关文章:

c++ - 使用 SOIL 使用 OpenGL 映射纹理

file - 在 Ember.js 中输入类型 ="file"

ios - 如何快速播放文档目录中的下一首轨道

android - 删除目录中最旧的文件,直到它小于特定文件大小

PHP脚本编译c++文件并使用输入文件运行可执行文件

c++ - (z-xi)^2 的最小化

c++ - fstream EOF 意外抛出异常

c++ - 自定义 std::fstream、std::filebuf 的上溢和下溢函数不会为每个字符调用

c++ - 无法读取 C++ 中的文本文件

c++ - 有没有一种方法可以自动链接 OpenGL 程序需要的所有库,而无需在编译时明确写入它们的标志?