I want to run my TCP project by command line
tcpserver --port 3333
How can do it and what should change in the c++ code?
Last edited on
Are you asking how to add command-line argument handling to your program?
Set up main like:
1 2 3 4
|
int main(int argc, char* argv[])
{
}
| |
argc is the number of arguments, and argv is an array of char* strings.
argv[0] is the name of the program itself on any mainstream shell.
So, for your example, argv[1] is "--port" and argv[2] is "3333".
You would do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
if (argc <= 2)
{
// not enough arguments
std::cerr << "Usage: tcpserver --port <number>\n";
return 1;
}
for (int i = 1; i < argc; i++)
{
if (std::string(argv[i]) == "--port" && i + 1 < argc)
{
const char* port = argv[i + 1];
std::cout << "Port: " << port << '\n';
}
}
}
| |
Last edited on
@Ganado thank you for replying to my question