-3

How do I combine cin and argv in a script?

int main(int argc, char* argv[])
c == argv[1];
cin >> c;

How do you ignore cin if there's a command line argument, or do cin if there's no command line argument?

Seb
  • 1,966
  • 2
  • 17
  • 32
  • 1
    `argc` gives you the count of arguments. If it's high enough for `argv[1]`, you can just set it, and input it if not. – chris Nov 29 '12 at 03:13

2 Answers2

1
string s;

if(argc == 2) 
    s = argv[1];
else
    cin >> s;

... do stuff here ...
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
1

The object std::cin and objects of class std::ifstream both share a common base class: std::istream. You can use this fact to pass either cin or an ifstream to a common function:

void DoOne(std::istream& in) {
  int x;
  in >> x; // etc etc
}

int main (int ac, char **av) {
  if(ac == 1)
    DoOne(std::cin);
  else {
    for(i = 1; i < ac; ++i) {
      std::ifstream inFile(av[i]);
      DoOne(inFile);
    }
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308