I am new to C and I have a small problem in understanding this scanf() line:
printf("Enter a message to add to message queue : ");
scanf("%[^\n]",sbuf.mtext);
How do I write this statement if I am getting the value from the command line?
I think I would have to declare the variable as a string?
If you are getting any value or data from command line then the command line arguments (click to open link) are very helpful
for using command line arguments, you must change you main() function definition from, let's say int main() to
int main ( int argc, char *argv[] )
here int argc is the argument counter. It is an integer and stores the number of arguments passed from the command line (+ the name of the program)
and char* argv[] is the argument vector which holds the data you sent into main function as strings
How do I write this statement if I am getting the value from the
command line?
As any value you entered at command line is stored in char *argv[], you can access the appropriate string this way
printf("%s",argv[command_no])
Example : (printing out value of argc and all strings stored in *argv[])
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("%d\n",argc);
for(int i=0;i<argc;i++)
{
printf("%s\n",argv[i]);
}
return 0;
}
Command line arguments :
these are command line arguments :)
Output:
6
E:\C-Programming\Workspace\Interview\Debug\Interview.exe
these
are
command
line
arguments
:)
Note : The first argument or the argv[0] is always the name of the program
Related
For example,
Input:
echo( hello world
Program:
#include<stdio.h>
int main(int n,char** args){
// Replace all the '\0' with ' '
system(args[1]);
return printf("\n");
}
Output:
hello world
Now I need hello world in a pointer.
I know that **char doesn't work the way I want it to..
But is there any efficient way out, instead of calculating the length of each argument, malloc-ing those many bytes and then concatenating it to the allocated memory?
Some access specifier for char** maybe?
I am trying to add echo( a command to DOSBox, so basically echo params and then print a newline. That's it.
Also, is there any way to exclude to recognize an exe without any spaces or is it console specific?
To echo an empty line, in Windows cmd, the best method is echo(, but also common are echo/, echo. and some more variations.
The (best for cmd) echo( doesn't work in DOS (results in a bad command or filename error), but echo/ works fine even in DOS.
Make it one line.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char oneline[256] = "";
for(int index = 1; index < argc; index++)
{
strcat(oneline, argv[index]);
strcat(oneline, " ");
}
printf("parameters: "%s"\n", oneline);
}
https://godbolt.org/z/B4ULLB
This is only the idea and it can be done much more efficiently - for example by not using strcat or more efficiently allocate the memory. But the idea will be the same. You can also do not add the last space (it is for nitpickers)
I want a way to get all the arguments in a single pointer, a string that's terminated at the end.
Using either form of the main() function:
int main(int argc, char *argv[]) {...};
int main(int argc, char **argv) {...};
which are equivalent signatures for the C main() function, will allow you to pass any number of arguments, each of any size. If you want to pass a single string containing many arguments just pass a single string with some kind of delimiter. If the delimiter is a space ( " " ), then by definition of the behavior of the C main() function command line argument requires surrounding them with ":
Say your exe name is prog.exe
prog this,is,one,argument
prog "this is one argument" //double quotes provide cohesion between space delimited command line arguments
prog this-is-one-argument
Will all be contained in a single variable: argv[1]
If you compile this as echo.exe it will put to stdout any thing typed into stdin:
int main(int argc, char **argv)
{
if(argv != 2) return 0;
fputs(argv[1], stdout);
return(0);
}
Usage: echo "this will be echoed onto stdout"<return>
Usage: abc000<return>
Usage: this-is-one-argument<return>
This question already has answers here:
What does int argc, char *argv[] mean?
(12 answers)
Closed 5 years ago.
in my C script my input is printing out gibberish and im not sure why
heres more or less what i have on it
int main (int arg, char argv[])
{
printf(argv);
}
this prints out giberish?
The following should yield the results you are looking for
#include <stdio.h>
int main(int argc, char **argv)
{
// Check if there is at least 2 arguments. First argument is the executable name.
if(argc > 1)
{
// Print out a string, followed by a new-line character.
printf("%s\n", argv[1]);
}
// Exit successfully
return 0;
}
Edit: After looking at your code here and some of the things I recommend to change:
The signature of your main function to int main(int argc, char **argv). Here argc is the argument count, and argv are the argument values. argv is a double-pointer. If we consider char* to be a string (sequence of characters in memory terminated by a null-character, or 0), then argv is a pointer to argc-many strings.
Secondly, to check the first program argument, consider making sure that there is in-fact an argument there. if(argc > 1) will make sure there is at least 1 argument to the program (the 0-index argument to a program is the executable path).
When you want to actually check the value of the first argument, de-reference argv to get a "string" with argv[1] //The first argument. Then you can de-reference this string to get the first character
if ( *(argv[1]) == 'f' )
{
....
}
If you want to check for a full string, rather than just a single character, consider using a function such as strcmp defined in <string.h>.
First of all, I'm working on a program in C that based on the input of the user it returns different things. I have this function that given a line a separator and an index it goes through the line and divides the string into substrings depending on the separator and returns the substring according to the index:
void get_substring(char line[], char result[], char separator, int index){
int i, j=0, my_index=0;
for(i=0; line[i] != '\0'; i++){
if(line[i]==separator)
my_index++;
else if(my_index == index)
result[j++]=line[i];
}
result[j]='\0';
}
So basically I write on the console /pmsg user Hello I'm John and I use the function get_substring() to save the user in a global variable char a_result2[] and the entire input line is saved in a global variable named a_message[]. The output of the function /pmsg should be:
**output : private message (user): Hello I'm John**
The problem is I don't know how to retrieve the entire message, because the message could be composed of a lot of words, and with my function get_substring I can only get the substring if I know the length of the message. I would appreciate it very much if you could help me, thanks. Here is the code for the function pmsg that I have already:
void pmsg(){
printf("output : private message (%s): ", a_result2);
}
If your compiled binary is called e.g. pmsg and you want to call it with arguments you have to use quotes around the message
./pmsg username "Hello I'm John"
and then use main's arguments. Here is an example:
int main(int argc, char const *argv[])
{
int i;
printf("output : private message (%s) : %s\n", argv[1], argv[2]);
return 0;
}
Here argv[1] is the username and argv[2] is the whole message.
Check how to use arguments with main here and here
I have just started learning C and I have a basic question. How do I read out a command line argument. For example, if I execute:
./main "test"
How can I get the command line parameter "test" into a variable:
int main(int argc, char **argv){
char s[] is supposed to equal "test"
}
EDIT: Basically I want to create a new char array that equals argv[1].
char * s = argv[1];//to read the test
if(strcmp(s,"test") == 0){
//the command line argument is equal to the string test
}
The arguments argc and argv of the main function are used to access the string arguments passed to your program when it is started. argc is the number of arguments passed. For example when run like this - ./myprogram arg1 arg2 arg3, argc will have a value of 4. This is because along with the strings the user passes in the name of the program is also passed. That is argv[0] points to a string myprogram, argv[1] points to arg1 etc. To get the nth argument then you must access argv[n + 1].
Knowing this, to make a copy of the first argument you can do as follows
char * s = malloc(strlen(argv[1]) + 1);
strcpy(s, argv[1]);
However I would advise making sure that the argument you want doesn't point to NULL before copying it. This is where argc is handy. Before accessing argv[1] I would check if argc >= 2.
There is a much better explanation here http://crasseux.com/books/ctutorial/argc-and-argv.html or here http://www.cprogramming.com/tutorial/c/lesson14.html
Edit:
Remember to free any memory you allocate via free
eg. free(s).
I've built a C application, and when I build it, it shows no errors, but when I run it, it gives me the error "Segmentation Fault: 11".
If it helps, here is the code I am using:
#include <stdio.h>
int main(char *argv[]) {
printf("The project path is: ./Projects/%c", argv[1]);
return 0;
}
The correct main prototyped syntax is
int main(int argc, char *argv[]) { ... }
Also %c conversion specification in printf prints a character, to print a string use %s.
You have a number of problems:
The signature for main is an argument count followed by an array of C strings.
You should always check the count before using the array.
The array is of strings so you need %s to print them.
This should work:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc < 2)
fprintf (stderr, "Wrong number of arguments\n");
else
printf ("The project path is: ./Projects/%s\n", argv[1]);
return 0;
}
Change the signature to int main(int, char*[]);
What arguments are you passing to the process? If you're not passing any argv[1] is out of range
In addition to the other suggestions, you may need to revisit your printf format. %c is used to print a single character, and argv[1] is char *. Either use argv[1][0] or some such, or use the string format specifier, %s.
First, change your main to:
int main(int argc, char *argv[])
Second, you have a mismatch between what you're passing to printf, and what you've told it you're going to pass. argv[1] is a pointer to characters, not a character. You need/want to use the %s conversion to print it out:
printf("The project path is: ./Projects/%s", argv[1]);
In this specific case, it's not really mandatory to check for enough arguments, because even if you don't pass any command line arguments, argv will contain at least argv[0] followed by a null pointer. As such, using argv[1] is safe, but if you haven't passed a command line argument, may print as something like (null).
Nonetheless, you generally want to check the value of argc before using argv. In this case, you can get away with it, but only more or less by accident. Trying to use argv[2] the same way could give undefined behavior.