0

I am using Unix shell to run my C++ executable files. The program I am writing requires having some values assigned to its variables. I want to assign values to these variables on the command line rather than having a user manually entering them. In the following program, I was able to do that by providing two arguments in the command line.

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv)
{
    int apples, oranges;
    apples = stoi(argv[1]);
    oranges = stoi(argv[2]);
    cout << "Total Fruits: " << apples + oranges << endl;
    return 0;
}

enter image description here

However, if my program has a cin>> line as shown in the following program, how can I assign values to apples and oranges variables without the user having to manually enter these values. I would like to assign values to cin>>apples and cin>>oranges at the command line run (similar to: program.exe 5 6)

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv)
{
    int apples, oranges;
    cin >> apples;
    cin >> oranges;
    cout << "Total Fruits: " << apples + oranges << endl;
    return 0;
}
D P.
  • 1,039
  • 7
  • 27
  • 56
  • 4
    What about `echo 5 6 | ./program`? – Evg Jun 30 '21 at 19:31
  • 1
    Tactical note: Never use `argv` without first consulting `argc`. – user4581301 Jun 30 '21 at 19:34
  • 1
    You can use `apples = stoi(argv[1]);` to read from the command line (`e.g. myprog 5 6` ) or `cin >> apples;` to read from the user. Q: So what exactly is your question? Evg's solution, `echo 5 6 | ./program`, does *NOT* read from argc/argv: it reads from "stdin". Which, maybe, is exactly what you're looking for? – FoggyDay Jun 30 '21 at 19:34
  • @Evg Thank you for all of your comments. I am trying to execute this in a website using PHP. So, are you suggesting using something like this `shell_exec( '5 6' | './somepath/program');` This specific line didn't work for me. Maybe I need to modify this? – D P. Jun 30 '21 at 19:44
  • 2
    I guess you need `'echo 5 6 | ./somepath/program'`. – Evg Jun 30 '21 at 19:45
  • 1
    @DP. Another way you can use is to generalize your input routines to take data from a `std::istream &` variable (function parameter), take the `argv[x]` to a `std::istringstream` and pass it to your function with the `std::istream &` parameter. Thus you can choose if the input should be taken via `std::cin` or any other input stream. – πάντα ῥεῖ Jun 30 '21 at 19:54
  • @Evg Thank you so much for helping me out. Yes, that was the answer I was looking for. Much appreciated. – D P. Jun 30 '21 at 19:55

0 Answers0