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).
Related
What would be the equivalent of the following Python code in C++?
import sys, os
#Example command
os.system(f"touch {sys.argv[1]}")
a close equivalent can be :
#include <cstdlib>
#include <iostream>
#include <string>
int main(int argc, char ** argv)
{
if (argc == 2)
{
std::string cmd = std::string("touch ") + argv[1];
std::system(cmd.c_str());
}
else
std::cerr << "Usage: " << argv[0] << " <file>" << std::endl;
return 0;
}
I preferred to check the number of args rather than to hope it is not just 1.
Anyway it is also possible to do that without using touch nor system or equivalent, your program creates the file if it does not exist, or to set its modification date&time to the current date&time
I'm slowly moving from using Python to using C++ and I don't understand how to run any code. I'm using the g++ compiler, but I get no results from my functions.
// arrays example
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}
If I run this example inside VSCode and specify that I want to use g++ compiler it comes back with: Terminal will be reused by tasks, press any key to close it.. If I compile it through cmd and run the task, a new cmd window flashes and nothing is happening.
I found the g++ doc which says how to compile with g++ and it shows the following example:
#include <stdio.h>
void main (){
printf("Hello World\n");
}
But I can't even run the compiler because it says
error: '::main' must return 'int'
void main(){
^
How can I print something in cmd or the ide terminal? I don't understand.
I believe you are using VSCode in a wrong way. You must know that it does not have integrated compiler by default but you need to compile source file in command line and run the executable:
$ g++ hello.cpp
$ ./a.out
Your first example runs with no problem. Check here
Your second example has an error because there is no void main() in C++. Instead, you need to have
int main() {
return 0;
}
UPDATE
If running the executable results in opening and closing the window you can fix that by using one of the following:
shortcut
#include <iostream>
using namespace std;
int main() {
system("pause");
return 0;
}
preferred
#include <iostream>
using namespace std;
int main() {
do {
cout << '\n' << "Press the Enter key to continue.";
} while (cin.get() != '\n');
return 0;
}
Why std::endl is not needed?
Some of the comments are suggesting that changing
cout << result;
to
cout << result << endl;
will fix the issue but, in this case, when the above line is the last line in the main function it really does not matter since program's exit flushes all the buffers currently in use (in this case std::cout).
I'm trying to implement a simple command line program that takes three arguments and prints them on the linux terminal
For example:
>c++ exec.cpp
>./a 32 + 32
Should print out contents like this
32
+
32
But the program is looping indefinitely
I've implemented a check for argc
Like this
if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}
In case the argument count is 3
These lines of code should be executed
else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}
But as I explained before the program loops indefinitely
EDIT:
Since I was asked to post the entire code here it is
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc,char* argv[]) {
if(argc!=3) {
cout << "Exit" << endl;
return -9999;
}
else {
for(int i=0;i<argc;i++){
cout << argv[i] << endl;
}
}
}
Your code is working...
I made slight modifications (eg. argc !=4 , i <= argc , etc. )
I compiled it using gcc (g++) on my linux system using:
g++ exec.cpp -o a.out
./a.out
Output:
Exit
When I run:
./a.out 4 + 3
Output:
4
+
3
Now with code, that does look okey to me in fact.
There doesn't seem to be a way to have an endless loop in every case.
What happens if you add return(0); to the very end of the main function?
Main always has to return something and compilers normally either complain or do that on their own hwoever if the propgrammer didn't add it.
Oh, have you tried the cerr variant instead of cout for your error message? Because returning from the main right after, is quite the same as the crash I mentioned.
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;
}
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!"