C++ 输入/输出流

问题描述 投票:0回答:1

我在 C++ 中的 I/O 流方面遇到问题。我必须编写一个程序,从文件读取数据并将其写入另一个文件。 CMD 中的命令应类似于:“program < file1 > file2”。文件的名称应该由用户提供(可以是随机的)。我写了一个代码,但它不正确。我不知道如何使用命令“> file2”将流重定向到文件。我可以在代码中更改哪些内容才能使其正常工作?有人可以帮助我吗?

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::string input_line;
    while (std::getline(std::cin, input_line)) {
        std::ofstream output_file("file2.txt", std::ios::app);
        if (!output_file.is_open()) {
            std::cerr << "Error" << std::endl;
            return 1;
        }

        output_file << input_line << std::endl;
        output_file.close();
    }

    return 0;
}
c++ iostream
1个回答
0
投票

我在 C++ 中遇到 I/O 流问题。

好的。

CMD 中的命令应类似于:“program < file1 > file2”

这意味着您正在使用 shell 来完成工作。这里。

<
>
是 shell“运算符”,用于将文件重定向到程序的标准输入和标准输出。这意味着您的程序应该从
std::cin
读取并写入
std::cout

您假设输出文件是“file2.txt”!

std::ofstream output_file("file2.txt", std::ios::app);

你总是在追加它。如果该文件已经存在,这可能不是您想要的,因为它会将新内容添加到任何旧内容上。我可能会改变它(如果我使用文件)。但更简单的解决方案是使用

std::cout
(如上所述)。

我假设您正在将其作为练习的一部分,因此请完成这些步骤。

#include <iostream>
#include <fstream>
#include <string>

int main() 
{
    std::string input_line;
    while (std::getline(std::cin, input_line)) {


        // This should open file is inside the loop. 
        // You should probably move it outside the loop.
        // A side effects of this is that you don't need to append
        // so you will destroy the old content and get rid of it.
        std::ofstream output_file("file2.txt", std::ios::app);

        if (!output_file.is_open()) {
            std::cerr << "Error" << std::endl;
            return 1;
        }

        // probably don't want to use `std::endl` here.
        // This forces a flush from the internal buffer to the hardware.
        // You probably just want to use `"\n"` here.
        output_file << input_line << std::endl;

        // You are closing the output file after writting one line to it.
        // May be more effecient to only close the file after writting
        // all the lines to the file.
        output_file.close();
     }

    return 0;
}

如果我是为一门试图理解流的课程写这篇文章。这就是我重写的方式:

#include <iostream>
#include <string>

int main() 
{
    std::string input_line;
    while (std::getline(std::cin, input_line)) {
        std::cout << input_line << "\n";
    }
    return 0;
}

注意:这并不十分完美,因为最后一行可能不包含换行符,但上面的代码总是为每一行添加换行符。我把它作为练习留给你来解决最后一个简单的问题。

© www.soinside.com 2019 - 2024. All rights reserved.