Loading File

Hi, I was wondering if someone could explain to me how to run a program in terminal with this format.
MyCode <Text.txt> <AnotherText.txt> <Flag>
The flag should determine what part of the Mycode to run.
Example flag = 1; Run thisFunction() or flag = 2; Should be able to Run thisOtherFunction();
Hope its not to confusing
Thanks
Yeah, try using int main's argc and argv arguments.

int main(int argc,char* argv[]);

and then an if statement to check.

Hope it HELPS!!!
Last edited on
To elaborate:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int main(int argc, char* argv[])
{
  if (argc < 4) 
  {
    cout << "Usage: MyCode <Text.txt> <AnotherText.txt> <Flag>" << endl;
    return 1;
  }
  
  string Text = argv[1];
  string AnotherText = argv[2];
  
  if (argv[3] == "1")
    thisFunction();
  else if (argv[3] == "2")
    thisOtherFunction();
  else 
    cout << "Invalid flag" << endl;
	
  return 0;
}
Last edited on
So I tried the example above however the argv[3] is never equal to "1" or "2". when the I type 1 or 2 in the terminal. I tried changing it to argv[3]== '1' but of course that cannot be since its pointer to int comparison. Any Idea How I can make it work?
Try
1
2
3
4
5
int main(int argc, char* argv[])
{
  for (int i = 0; i < argc; i++)
    cout << argv[i] << endl;
}


That will tell you what you are getting.
I actually checked before and the result is correct that argv[3] hold, however the: if(argv[3] == "1"){}
will not execute even though the argv[3] is equal to 1, which is confusing?
I got it to work by creating two string i = "1" and string x = "2". Then use if(argv[3] == i)
Well that's interesting. Might be a dually terminated string (i.e. 1 \0 \0)
dually terminated string (i.e. 1 \0 \0)


WOW!! HAHAHAAA!!!!
I actually checked before and the result is correct that argv[3] hold, however the: if(argv[3] == "1"){}
will not execute even though the argv[3] is equal to 1, which is confusing?


It's not that confusing. The address of "1" was not equal to the address stored in argv[3]. What those addresses pointed to wasn't compared.

When you compared argv[3] to a std::string type, you actually compared the contents so the outcome was as you expected.
Topic archived. No new replies allowed.