如何在C++中将文本重定向到文件

How to redirect text to a file in C++

本文关键字:文本 重定向 文件 C++      更新时间:2023-10-16

我正在尝试编写一个小型自动化程序,为我计算一些值,并将一些文本输出到一个简单的.txt文件中。执行重定向符号<>&lt<>>在C++中的工作与在批处理脚本的命令行中的工作相同吗?当我尝试在C++中搜索如何重定向到.txt文件时。我发现的所有示例和教程都是以如下方式在控制台上假设IO的。

    cout::<<"show this text on the console";
    cin::>> whatever you would call here to accept user input.

我想知道的是这样做行吗?

    #include <string>
     using namespace std;
    int main()
    {
        int X = 0;
        string zero = "touchPress 0 483 652n";
    if {
     (X=0)
    zero>>C:test.txt;
    x+5;
   } return 0;

}

您的代码不起作用。我不完全确定所需的行为是什么,但这段代码将字符串zero写入一个文件:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() 
{
    int X = 0;
    string zero = "touchPress 0 483 652n";
    ofstream myFile("C:\Data\test.txt");
    //a condition which is always true
    if (X==0)
    {
      myFile<<zero;
      X + 5; //this is valid but useless
    }
    return 0;
}
    #include <fstream>
    int main(){
        string zero = "touchPress 0 483 652n";
        std::ofstream fout("test.txt"); // creates new test.txt in folder where .exe is
        fout << zero; //same as cout << zero;//but in the file
        return 0;
    } 

作为cout,我刚刚重新设计了你勉强活着的程序。这是你想要的吗?