如何通过脚本将输出写入C++中的文本文件

How can I write output to text file in C++ by script

本文关键字:C++ 文本 文件 何通过 脚本 输出      更新时间:2023-10-16

我写了一段代码来创建两个给定范围的随机数。我想写输出结果(两个随机数)。在脚本文件中,我想将每次迭代的输出写在同一行中,作为我的预期结果

我当前的输出是

1 0   
1 0   
2 1  
2 3   
0  0   //output of second iteration
1  1 
2  2
1  3

我的预期结果是

1 0   0  0
1 0   1  1 
2 1   2  2
2 3   1  3

这是我的完整代码

#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <time.h>       /* time */
#define random(x) (rand()%x)
int main(int argc, char **argv) {
    unsigned int time_ui = static_cast<unsigned int>( time(NULL) );
    srand( time_ui );
    int number1;
    int number2;
    int range=atoi(argv[1]);
    number1 = random(range);
    number2 = random(range);
    //std::cout<< number1 << "t" <<number2;
    std::ofstream myfile;
    myfile.open ("report.txt", std::ios::app);
    myfile << number1 << "t" <<number2<<'n';
    myfile.close();
    return 0;
}

我的脚本文件是

#!/bin/bash
a=1
iter=0
for ((iter; iter <= 1; iter++))
do
    a=1
    while [ $a -lt 4]
    do
      ./random_num $a
      a=`expr $a + 1`
    done
done

请注意,您在C++代码中输出了一个换行符,这使得几乎不可能"取消输出"。我建议将逻辑从bash转移到C++代码中,反之亦然。C++有一些选项,比如setfill,可以帮助你控制它。