【问题标题】:Using I/O streams to read from one file and write to another使用 I/O 流从一个文件读取并写入另一个文件
【发布时间】:2019-02-14 04:27:42
【问题描述】:

我正在阅读一本教科书,其中的练习需要从一个文件中复制文本并将其写成与另一个文件等效的小写字母。我似乎找不到仅使用 I/O 流的方法(我在网上找到的大多数解决方案都使用流缓冲区)。

我的代码是这样的

int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';

cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};

fs << "LoRem ipSUM teXt TaXi";

char ch;

while (fsi.get(ch)) {


    fs2 << ch;
}

运行后没有任何内容写入第二个文件 (f_name2)。这只是一个空白文件。

编辑:

这也不行

int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';

cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};

fs << "LoRem ipSUM teXt TaXi";

char ch;

while (fsi>>ch) {


    fs2 << ch;
}

}

【问题讨论】:

  • 为什么f_name1打开了2次。
  • @drescherjm 前面的练习需要分别使用 ifstream 和 ofstream。我重新使用了旧代码。

标签: c++ file io


【解决方案1】:
  1. 你使你的任务复杂化,却没有明显的收获。没必要

    ofstream fs{ f_name1 };
    fs << "LoRem ipSUM teXt TaXi";
    
  2. 使用文本编辑器并在程序外部创建输入文件的内容。

这是您的 main 函数的更新版本:

int main()
{
   string f_name1, f_name2;
   cout << "enter the file names" << '\n';

   cin >> f_name1 >> f_name2;

   ifstream fs1{f_name1};
   if ( !fs1 )
   {
      std::cerr << "Unable to open " << f_name1 << " to read from.\n";
      return EXIT_FAILURE;
   }

   ofstream fs2{f_name2};
   if ( !fs2 )
   {
      std::cerr << "Unable to open " << f_name2 << " to write to.\n";
      return EXIT_FAILURE;
   }

   // Using ostream::put() seems the right function to use
   // for writing when you are using istream::getc() for reading.
   char ch;
   while (fs1.get(ch))
   {
      fs2.put(std::tolower(ch));
   }
}

【讨论】:

  • 使用 ostream::put() 代替
  • @Ajtsh,我不知道为什么这对你不起作用。它适用于我的电脑。
  • @R Sahu 在输出到第一个文件后使用 fs.flush() 解决了它。
  • @Ajtsh,很高兴听到。在您接受另一个答案后,我假设了很多:)
【解决方案2】:

嗯。因此,您正在写入文件,然后读取内容并再次写出。好吧...

您可能需要在 fs

我还会在你的 while 循环中添加一些打印语句,以确保你得到你认为你得到的东西。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2021-01-23
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2012-10-22
    相关资源
    最近更新 更多