printf causes crash - c++

#include <stdio.h>
int main(char sendbuf[100])
{
printf (sendbuf);
return 0;
}
Somehow this very basic program crashes when I try to use it, it's meant to print up whatever is typed as a parameter. If I remove the line "printf (sendbuf);" the crash goes away.

The first argument to main is the number of parameters. The second argument is an array of strings. The first element (index 0) of the second argument is the name of your program:
#include <stdio.h>
int main(int c, char **argv)
{
printf ("%s\n", c > 1 ? argv[1] : "No Argument");
return 0;
}

Your first parameter must be an integer, not a char array. Here is the right program:
#include <stdio.h>
int main(int argc, char* argv[])
{
if (argc > 1) {
printf( argv[1] );
}
else {
printf( "No arguments provided" );
}
return 0;
}
argv[0] is your program name, so argv[1] is the first parameter provided on teh command line.

C supports two forms of main function:
int main() { /* ... */ }
and
int main(int argc, char* argv[]) { /* ... */ }
To take parameter from main, you need to change your code to:
#include <stdio.h>
int main(int argc, char* argv[])
{
if (argc > 1){
printf ("%s\n", argv[0]);
}
return 0;
}
Or use stream:
#include <iostream>
int main(int argc, char* argv[])
{
if (argc > 1){
std::cout << argv[0]) << std::endl;
}
return 0;
}
argv[0] is application name, input parameters starts from argv[1] if any.

An implementation must support the following two definitions of main:
int main() { }
int main(int argc, char* argv[]) { }
It is implementation-defined whether they support any other definitions. I don't know of any implementation that allows int main(char*) though (which is what yours is equivalent to).

This will print everything you type on the command line after the program name, even with spaces. It will not crash if you type nothing after the program name.
#include <stdio.h>
int main(int argc, char **argv)
{
for(int i=1; i<=argc; ++i) {
printf("%s\n", argv[i]);
}
}

Related

Passing std::string as input to getopt()

I have a program that basically looks like this:
#include <iostream>
#include <unistd.h> // getopt
#include <vector>
#include <string>
#include <list>
#include <sstream>
using namespace std;
//a parameter structure to store parameters provided through console
typedef struct pairwise_param {
double alpha;
double beta;
} param;
//parse the parameter values
void param_getopt(param *pm, int argc, char **argv) {
int opt;
while((opt = getopt(argc, argv, "a:b:")) != -1) {
switch(opt) {
case 'a':
pm->alpha = atof(optarg);
break;
case 'b':
pm->beta = atof(optarg);
break;
}
}
}
int main(int argc, char* argv[]) {
//initialize param structure
param pm;
//pass command line arguments to param
param_getopt(&pm, argc, argv);
//do something to the parameters
std::cout << "Alpha: " << pm.alpha << std::endl;
std::cout << "Beta: " << pm.beta << std::endl;
return(0);
}
By making a header file and changing the main function to someother name, e.g. int main(int argc, char* argv[]) -> int maincomp(int argc, char* argv[]) I want to call the new function maincomp() from another program but instead of passing command line arguments I want to pass the arguments through a std::string.
I thought I could do something like this but it does seem to have some issues with getopt() that Im not entirely certain why. Currently anything that is written to console using for example std::cout after getopt() is called will not be displayed. It looks like what is passed to getopt() currently is not correctly type converted. My question therefore is how should one type cast a std::string to conform to the char * const argv[] input requirement of getopt(int argc, char * const argv[])?
int main(int argc, char* argv[]) {
//create string and pass it to maincomp
std::string cmd = "-a2.3 -b3.2";
std::istringstream ss(cmd);
std::string arg;
std::list<std::string> ls;
std::vector<char*> newargv;
while (ss >> arg) {
ls.push_back(arg);
newargv.push_back(const_cast<char*>(ls.back().c_str()));
}
newargv.push_back(0);
int out = maincomp(newargv.size(), &newargv[0]);
return(out);
}
The entire code:
https://onlinegdb.com/tjMC-LwiP
Using wordsexp.h solved the issue by parsing the string correctly for getopt().
Essentially:
//create string and pass it to maincomp
std::string cmd = "-a2.3 -b3.2";
//convert string with wordexp
wordexp_t newargv;
newargv.we_offs = 1;
wordexp(cmd.c_str(), &newargv, WRDE_DOOFFS);
//create a new argc
int newargc = newargv.we_wordc + newargv.we_offs;
//pass to maincomp function
int out = maincomp(newargc, newargv.we_wordv);
Full code:
#include <iostream>
#include <unistd.h> // getopt
#include <vector>
#include <string>
#include <wordexp.h>
typedef struct pairwise_param {
double alpha; double beta;
} param;
void param_getopt(param *pm, int argc, char **argv){
int opt;
while((opt=getopt(argc,argv,"a:b:"))!=-1){
switch(opt){
case 'a': pm->alpha = atof(optarg); break;
case 'b': pm->beta = atof(optarg); break;
}
}
}
int maincomp(int argc, char* argv[]){
//initialize param structure
param pm;
//pass command line arguments to param
param_getopt(&pm, argc, argv);
std::cout << "Alpha: " << pm.alpha << std::endl;
std::cout << "Beta: " << pm.beta << std::endl;
return(0);
}
int main(int argc, char* argv[]) {
//create string and pass it to maincomp
std::string cmd = "-a2.3 -b3.2";
//convert string with wordexp
wordexp_t newargv;
newargv.we_offs = 1;
wordexp(cmd.c_str(), &newargv, WRDE_DOOFFS);
int newargc = newargv.we_wordc+newargv.we_offs;
//pass to maincomp function
int out = maincomp(newargc, newargv.we_wordv);
return(out);
}
Produces the expected output:
Alpha: 2.3
Beta: 3.2

Under VS2019, CRT call the function main() with 3 auguments, why doesn't the Complier report error "incorrect number of parameters"?

In the file exe_common.inl, crt call main function like this:
static int __cdecl invoke_main()
{
return main(__argc, __argv, _get_initial_narrow_environment());
}
However, if I call main in my program with three auguments, C2660 error will occur.
just like:
#include <iostream>
using namespace std;
int index{ 10 };
int argv{ 1 };
char** argc{ NULL };
char* env{ NULL };
int main(/*int argc, char** argv, char* env*/)
{
cout << "index=" << index << endl;
if (index != 0)
{
index--;
main(argc, argv, env);
}
}
I am so curious about the startup code, so thank you for you answer.

Command line Argument c++

I have a program that requires a command line argument to run properly, but it runs even when no argument is provided. How do I ensure that an argument is provided before it runs?
int main(int argc, const char ** argv) {
std::ifstream b(argv[1]);
Word c;
c.fillWords(c.getWordsAdress(), &b);
c.printWord(c.getWordsAdress());
}
Check the argument count like this:
int main( int argc, const char* argv[] )
{
if (argc < 2)
return 1;
// your code here
}
You can just check the argument count and if it is less than 2, that means that no arguments were provided. The argument count will always have at least 1, which contains the name of the program.
int main(int argc, char** argv)
{
if(argc < 2) {
cerr << "usage: " << argv[0] << " -argument";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}

C++ CMD input along with exe

Sorry for such a noobie question, but how can I get a program to read the data i input with my program, like how cmd does it with the options
shutdown.exe -f
how do i read the example -f into my program?
This should print out each of the whitespace delimited parameters which were passed to your program.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
for(int i = 0; i < argc; i++)
{
printf("%s\n", argv[i]);
}
return 0;
}
If you're using plain old C++, your main function will need to look something like this:
int main(int argc, char *argv[])
where argc is the number of whitespace separated items, and argv is an array of pointers to each one
int main(int argc, char *argv[])
{
}
arguments are passed by argv.

How to get 1st parameter in main() in C++? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Pass arguments into C program from command line.
mypro parameter
When run like above,how to get the parameter in mypro's main() :
#include <iostream>
int main()
{
char* str = "default_parameter";
if(parameter_exists())str = parameter;
...
}
How to implement the pseudo code above?
Just need to add (int argc, char *argv[]) to your main function. argc holds the number of arguments, and argv the arguments themselves.
int main(int argc, char *argv[])
{
std::string str = "default";
if (argc > 1) { str = argv[1]; }
}
Note that the command is also included as an argument (e.g. the executable). Therefore the first argument is actually argv[1].
When expecting command-line arguments, main() accepts two arguments: argc for the number of arguments and argv for the actual argument values. Note that argv[0] will always be the name of the program.
Consider a program invoked as follows: ./prog hello world:
argc = 3
argv[0] = ./prog
argv[1] = hello
argv[2] = world
Below is a small program that mirrors the pseudocode:
#include <iostream>
#include <string>
int main(int argc, char **argv) {
std::string arg = "default";
if (argc >= 2) {
default = argv[1]
}
return 0;
}
Your function should use the second of these two allowed C++ main function signatures:
int main(void)
int main(int argc, char *argv[])
In this, argc is the argument count and argv is an argument vector.
For more details, see this Wikipedia article.
Well you need a main function that accepts arguments, like so:
int main(int argc, char *argv[])
{
}
You would then check the number of arguments passed in using argc. Usually there is always one, the name of the executable but I think this is OS dependent and could thus vary.
You need to change the main to be:
int main(int argc, char** argv){
argc is the number of paramaters, argv is an array containing all of the paramaters (with index 0 being the name of the program). Your first parameter will be located at index 1 of argv.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
for(int i = 1; i < argc; i++)
cout << atoi(argv[i]) << endl;
return 0;
}
Here argc gives the count of the arguments passed
and argv[i] gives ith command line parameters.
where argv[0]='name of the program itself'
main has two parameters, int argc and char** argv which you can use to access to the command line parameters.
argc is the number of parameters including the name of the executable, argv points to the parameter list itself (so that argv[0] is "mypro" in your example).
Just declare main like
int main (int argc, char** argv){..}
You need to use this declaration of main:
int main(int argc, _TCHAR* argv[])
{
if (argc > 1)
{
str = argv[1];
}
}
argv[0] is the name of the executable, so the parameters start at argv[1]
On Windows, use the following signature instead to get Unicode arguments:
int wmain(int argc, wchar_t** argv)