First thing,sorry my bad english and any mistakes in asking.
I've searched it a lot,but i was not able to explain in simple words.
I work with Linux servers and command line, i'm used to calling programs through it like
./program foo -u adm -p 123
But i always wondered how make programs to act like that,i mean call a specific function and write parameters without needing to open program itself.
In other words.
If i code a C++ like that,and compile
#include <iostream>
using namespace std;
void SayHello(string Name)
{
cout << " Hello " << Name;
}
how can i call it through the command line like
./Program SayHello CARLOS
Sorry about my ignorance,but it's something that i want to learn.
Thanks for your attention
If you want to call a function of your program based on the arguments, you could do something like:
int main(int argc, char* argv[]) {
if(argc > 2){
if(strcmp(argv[1], "SayHello") == 0){
SayHello(argv[2]);
}
}
return 0;
}
Of course this is just a sketch and i can be improved if what you want to achieve is more complex.
You could also build a more dynamic solution if you want other functions than the "SayHello" one to be callable too.
int main( int argc, char** argv )
Here argc refers to the number of argument (arg count)
argv refers to the argument array ("char*" array) (arg value)
Calling your program from command line will result in a main entry with these parameters ; it remains to parse them and launch the command accordingly.
void main() {
char *name[] = {
"./program",
"-c",
"foo -u adm -p 123",
NULL
};
execvp(name[0], name);
}
There you go every executable needs a main function which is the entry point for execution.
#include <iostream>
#include <string>
using namespace std;
void SayHello(string Name)
{
cout << " Hello " << Name;
}
int main(int argc, char* argv[])
{
if (argc > 1)
SayHello(argv[1]);
}
To compile this do
$g++ hello.cpp
It should produce a.out on Linux.
To run it
./a.out "World!"
Related
When I run my C++ program I need it to open a text file stored in my root directory. How can I make CMake to execute the program I have written with the text file?
When I build my program with Makefile alone, I use the command
./"executable" src/"txt file"
Honestly, by far the simplest would be to just modify your main function. As it stands you main function must be grabbing the filename from the command line arguments. Something like this:
#include <iostream>
int main(int argc, char *argv[]) {
const auto filename = argv[1];
// Do stuff with filename
std::cout << filename;
return 0;
}
What you probably should do is to just modify that file to use some default filename when no argument is provided:
#include <iostream>
int main(int argc, char *argv[]) {
const auto filename = argc < 2 ? "/root/something.txt" : argv[1];
// Do stuff with filename
std::cout << filename;
return 0;
}
Depending on how complicated you want to get, you could also let that filename be specified in your CMakeLists. Just add a definition like
set(DEFAULT_FILENAME "/root/something.txt")
target_compile_definitions(my_target PRIVATE "DEFAULT_FILENAME=\"${DEFAULT_FILENAME}\"")
and then take the filename like a macro in your main function:
#include <iostream>
int main(int argc, char *argv[]) {
const auto filename = argc < 2 ? DEFAULT_FILENAME : argv[1];
// Do stuff with filename
std::cout << filename;
return 0;
}
To summarize... It sounds like you want to have one executable to be built with the filename into it. The aforementioned approaches will accomplish that.
However, there is a much simpler solution... just create a script that runs the file you want. For example, just throw your code
./"executable" src/"txt file"
into a script run.sh
Then make that script runnable (assuming Linux) with
chmod +x run.sh
and just run that script:
./run.sh
I have a simple program, e.g. in C++
#include<iostream>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b;
c = a + b;
cout << c;
}
Here i need to give a and b as inputs at the time of execution.
I need to write a script to auto type value of a (say 5) and b (say 7) into the first terminal.
I think you have to change something to do so, as you want to pass the arguments from the script.
C++ program main.cpp:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc,char *argv[])
{
if(argc==1)
{
exit(1);
}
int a=atoi(argv[1]);
int b=atoi(argv[2]);
cout<<a+b<<endl;
return 0;
}
and shell script will be :
#!/bin/bash
g++ temp.cpp -o out
a=5
b=2
./out "${a}" "${b}"
You should see here for passing variables.And see this also
Instead of trying to write a program that interacts with multiple terminals or works with pipes, which might be more complicated, I'd recommend making your program simpler by having it handle command-line arguments. You can re-write your C++ program as follows:
#include <iostream>
#include <cstdlib> // for atoi function
using namespace std;
int main(int argc, char* argv[]) // to accept CLI inputs
{
// argv[0] has path/name to this program
// argv[1] has 1st argument, if provided
// argv[2] has 2nd argument, if provided
// if argc != 3, then we don't have everything we expected, and we bail
if(argc != 3) {
cerr << "usage: " << argv[0] << " arg1 arg2" << endl;
return -1;
}
// for simplicity, we assume that you won't get letters, only numbers
int a = atoi(argv[1]);
int b = atoi(argv[2]);
cout << (a + b);
return 0;
}
You can then write a simple shell script to launch your program with whatever arguments you want. For example, if your built program is called test (use g++ -o test test.cpp to build), then you can use this example launcher.bash script:
#!/bin/bash
for i in {0..10}
do
./test $i $i
echo
done
The script produces the following output:
/tmp ❯ ./launcher.bash
0
2
4
6
8
10
12
14
16
18
20
If the executable is a.out then you can use
a=5;b=7;echo $a $b | ./a.out
Btw, in your example the namespace for cout/cin is missing (for e.g. add using namespace std; after the #include).
I search a lot but don't find nothing.
I want make a C++ software to run a software with argument in C++
Example : start putty -ssh user#server -pw password
start notepad -someargument
To start a different software than your own program (with or without arguments) you can use system() from <cstdlib> header.
#include <cstdlib>
int main(int argc, char* argv[]) {
system("start putty -ssh user#server -pw password");
return 0;
}
If you want to evaluate the arguments to your own program, you can use argv[]. argv[0] holds the name/path of your program, and argv[1] ... argv[argc-1] the actual arguments i.e.
#include <cstring>
#include <iostream>
int main(int argc, char* argv[]) {
if ((argc > 1) && (!strcmp(argv[1], "-help"))) {
std::cout << "Showing help" << std::endl;
}
return 0;
}
I need help because I am not getting the expected output while attempting to read the command line arguments. It is really strange because I copied and pasted the code into a regular console application and it works as expected. It is worth noting that I am running Windows 7 and in visual studio I set the command line argument to be test.png
Win32 Code:
#include "stdafx.h"
using namespace std;
int _tmain(int argc, char* argv[])
{
//Questions: why doesn't this work (but the one in helloworld does)
//What are object files? In unix I can execute using ./ but here I need to go to debug in top directory and execute the .exe
printf("hello\n");
printf("First argument: %s\n", argv[0]);
printf("Second argument: %s\n", argv[1]);
int i;
scanf("%d", &i);
return 0;
}
Output:
hello
First Argument: C
Second Argument: t
I tried creating a simple console application and it works:
#include <iostream>
using namespace std;
int main(int arg, char* argv[])
{
printf("hello\n");
printf("First argument: %s\n", argv[0]);
printf("Second argument: %s\n", argv[1]);
int i;
scanf("%d", &i);
return 0;
}
Output:
hello
First Argument: path/to/hello_world.exe
Second Argument: test.png
Does anyone have any idea what is going on?
_tmain is just a macro that changes depending on whether you compile with Unicode or ASCII, if it is ASCII then it will place main and if it is Unicode then it will place wmain
If you want the correct Unicode declaration that accepts command line arguments in Unicode then you must declare it to accept a Unicode string like this:
int wmain(int argc, wchar_t* argv[]);
You can read more about it here
Another issue with your code is that printf expects an ASCII C Style string and not a Unicode. Either use wprintf or use std::wcout to print a Unicode style string.
#include <iostream>
using namespace std;
int wmain(int argc, wchar_t* argv[])
{
//Questions: why doesn't this work (but the one in helloworld does)
//What are object files? In unix I can execute using ./ but here I need to go to debug in top directory and execute the .exe
std::cout << "Hello\n";
std::wcout << "First argument: " << argv[0] << "\n";
std::wcout << "Second argument: " << argv[1] << "\n";
return 0;
}
I am building a web application / Interface for my C++ program which will be hosted on the server and then using a scripting language ("PHP") I will then execute the program to run.
I am using G++ to compile the code and and I execute the command to run like so: ("./main") now is it possible that I can pass in the file location so then my program can run? So for example like this:
int main(int argc, char *argv[], string* fileLoc)
{
// code
}
Then execute like this ("./main(FILE_LOCATION)")?
Hope someone can help
You should keep the standard main signature int main(int argc, char *argv[]). The filename would be in argv[1], provided you execute it like this:
./main somefilename.txt
//main.cpp
#include <iostream>
int main(int argc, char* argv[])
{
if (argc > 1)
std::cout << argv[1] << "\n";
}
./main Hello_there
Hello_there