Skip to content
Advertisement

How to pass inputs (not arguments) thorugh command line in C/C++?

Say I have the following simple C++ program,

#include <bits/stdc++.h>
using namespace std;

int main() { //no argv or argc allowed
    cin >> t;
    while(t--) {
        int n;
        cin >> n;
        // do whatever
    }
}

and the following command in terminal:

g++ -std=c++17 -O2 -lm b.cpp && ./a.out

When I run this command, it will ask for my input and I have to copy and paste over the input like the following:

7
1 2 
2 4 
2 6
7 5
3 6
4 6
7 2

Is there a way for this to happen in one pass? I don’t mind copy and pasting each time, however I am planning on making a shell script to automate this for me. Basically, it takes the input stored in a remote HTTP server, and then passes it through a C++ program. The caveat is, for some reason I am not allowed to write files, so I can’t do fstream/freopen.

Advertisement

Answer

Process substitution is not the right way to do this. Use a heredoc:

g++ -std=c++17 -O2 -lm b.cpp && ./a.out << EOF
7
1 2 
2 4 
2 6
7 5
3 6
4 6
7 2
EOF
Advertisement