How can we reference just the string? - c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXSTR 255
#define ARGCNT 5
int main(int argc, char *argv[])
{
char cmd[MAXSTR];
char arg1[MAXSTR];
char arg2[MAXSTR];
char file[MAXSTR];
printf("cmd->");
fscanf(stdin, "%s", cmd);
printf("char %lu=%d\n",strlen(cmd),cmd[strlen(cmd)]);
printf("cmd->");
fscanf(stdin, "%s", arg1);
printf("char %lu=%d\n",strlen(arg1),arg1[strlen(arg1)]);
printf("cmd->");
fscanf(stdin, "%s", arg2);
printf("char %lu=%d\n",strlen(arg2),arg2[strlen(arg2)]);
printf("cmd->");
fscanf(stdin, "%s", file);
printf("char %lu=%d\n",strlen(file),file[strlen(file)]);
char ** args = malloc(sizeof(char) * ARGCNT);
*(args + 0) = cmd;
*(args + 1) = arg1;
*(args + 2) = arg2;
*(args + 3) = file;
*(args + 4) = NULL;
int *a = *(args + 2);
printf("TEST =%ls\n",a);
for (int i=0;i<ARGCNT;i++)
printf("i=%d args[i]=%s\n",i,*(args + i));
int status = execvp(args[0], args);
printf("STATUS CODE=%d\n",status);
return 0;
}
It is the output. TEST =d
cmd->a
char 1=0
cmd->s
char 1=0
cmd->d
char 1=0
cmd->f
char 1=0
TEST =d
i=0 args[i]=a
i=1 args[i]=s
i=2 args[i]=d
i=3 args[i]=f
i=4 args[i]=(null)
STATUS CODE=-1
How to print the args = arg2? Expect print "arg2" in print("TEST")
OR print "cmd" when a = args + 0
OR print "file" when a = args + 3
The output is the string that I input to args2 now.
Example: input is "ABC", the print will be ABC.
I want to print the string "arg2" instead of what I input.

You need to de-reference each arg, e.g.:
printf("%s",*argv[i]);
I would also advise re-formatting your question to make it clearer where you are confused.
This is also a duplicate: printing argv[]

Related

generating main arguments without the parameter

In C programming language, is it possible to access int argc or char **argv without using the parameters? I know some of you might ask why this is needed, just for research purposes.
Is it possible to generate the cmd line arguments without using the main parameter variables ? For example, to illustrate some pseudo code, that i have in mind,
LPTSTR cmd = GetCommandLine();
splitted = cmd.split(" ") //split from spaces
char **someArgv.pushForEach Splitted, length++
and you'd have a someArgv with the parameters and length as argc, this'd really help to know if possible to illustrate.
If OP already has the command as a string, then:
Form a copy of the string
Parse it for argument count
Allocate for argv[]
Parse & tokenize copy for each argv[]
Call main()
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// Not standard, but commonly available
char *strdup(const char *s);
// Return length of token and adjust offset to the next one
// Adjust as needed
// Presently only ' ' are used to separate
// More advanced would have escape characters, other white-space, etc.
size_t tokenize(const char *s, size_t *offset) {
// find following space
size_t len = strcspn(s + *offset, " ");
*offset += len;
// find first non-space
*offset += strspn(s + *offset, " ");
return len;
}
int call_main(const char *cmd) {
char *cmd2 = strdup(cmd);
cmd2 += strspn(cmd2, " "); // skip leading spaces
size_t offset = 0;
int argc = 0;
while (tokenize(cmd2, &offset) > 0) {
argc++;
}
char **argv = malloc(sizeof *argv * ((unsigned)argc + 1u));
offset = 0;
for (int a = 0; a < argc; a++) {
argv[a] = &cmd2[offset];
size_t len = tokenize(cmd2, &offset);
argv[a][len] = '\0';
}
argv[argc] = NULL;
int retval = 0;
#if 0
retval = main(argc, argv);
#else
printf("argc:%d argv:", argc);
for (int a = 0; a < argc; a++) {
printf("%p \"%s\", ", argv[a], argv[a]);
}
printf("%p\n", argv[argc]);
#endif
free(cmd2);
free(argv);
return retval;
}
Sample
int main() {
call_main(" name 123 abc 456 ");
}
argc:4 argv:0x800062322 "name", 0x800062327 "123", 0x80006232c "abc", 0x800062331 "456", 0x0
Pedantic: The strings provided to main() should be modifiable. Avoid code like
argv[1] = "Hello";
....
main(argc, argv);
#include <stdio.h>
int main(int argc, char *argv[]);
int callMain(void)
{
char *argv[4];
argv[0] = "binary";
argv[1] = "param1";
argv[2] = "param2";
argv[3] = NULL;
return main(3, argv);
}
int main(int argc, char *argv[])
{
if (argc <= 1)
{
return callMain();
}
printf("ARGC: %u\n", argc);
int i;
for (i = 0; i < argc; i++)
printf("ARG: %u - %s\n", i, argv[i]);
return 0;
}

How do I concatenate strings via command line arguments separated by a +?

What I want to do is write arguments in the command line separated by a + and concatenate the arguments into a single string
eg:
./concat Wow + this + is + cool
Wow this is cool
I looked up a question for this sort of topic before but that involved concatenating only the first character of each argument and not the entire arguments. And it didn't ignore the separator
This is what I have
void concat(char **argv, int argc, char *string)
{
size_t i = 0;
for(int j=1; j<argc; j++)
{
string[i++] = *argv[j];
if(j+1 != argc)
{
string[i++] = ',';
string[i++] = ' ';
}
}
string[i] = '\0';
}
And this is what I'm doing in main to call this function
int main(int argc, char *argv[])
{
int allnum=0;
char string[1000];
concat(argv, argc, string);
printf("%s\n", string);
}
Using the strcpy or strcat in string.h is more simple to concatenate string.
For example:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char * s = malloc (2 * argc *sizeof (char));
if (argc < 2)
exit(-1);
for(int i = 1; i < argc; i += 2) {
strcat(s, argv[i]);
strcat(s, " ");
}
printf("%s\n", s);
return 0;
}

How to get argv[k] into another string?

int main(int argc, char **argv){
char Q[MAXCHAR];
Q=argv[k+1];}
Q is an array while argv[k+1] is a pointer.
How can I get the content of argv[k+1] into Q?
You can use snprintf
snprintf(Q, MAXCHAR, "%s", argv[k]);
(edited : first version recommended strncpy).
You can't directly assign Q = argv[k+1]. For an array (Q[MAXCHAR]), arrayname (Q) is the base address. The base address of an array can't be changed.
Assuming k = 0, you can use any of the following to get the argv[1] data into Q.
memmove(Q, argv[1], strlen(argv[1]) + 1);
or
snprintf(Q, strlen(argv[1]) + 1, "%s", argv[1]);
or
strncpy(Q, argv[1], strlen(argv[1]) + 1);
or
memcpy(Q, argv[1], strlen(argv[1]) + 1);
or
sprintf(Q, "%s", argv[1]);
or
strcpy(Q, argv[1]);
Here is the program and it's output using memmove:
#include <stdio.h>
#include <string.h>
#define MAXCHAR 20
int main(int argc, char **argv)
{
if (argc < 2) {
puts("Not enough arguments");
return -1;
}
char Q[MAXCHAR] = {0};
memmove(Q, argv[1], strlen(argv[1]) + 1);
puts(Q);
return 0;
}
Output:
me#linux:~$ ./a.out stackexchange
stackexchange

How to separate argv[] input to two different strings on C?

I am new in programming and currently learning on C. Could you please assist me on solving below's case?
An example of this will be if a user is entering "cbamike", I would like to separate it into two strings: cba and mike.
I tried below's code but it doesnt work:
#include <stdio.h>;
int main (int argc, string argv[])
{
char* input[50] = argv[1];
char* first[10];
char* second[10];
sprintf(first, "%c %c %c", input[0], input[1], input[2]);
sprintf(second, "%c %c %c %c", input[3], input[4], input[5], inpput[6]);
printf("%s\n", input);
printf("%s\n", first);
printf("%s\n", second);
}
There is no string in c,
you can use strncpy to get first few characters as aswered there: Strings in c, how to get subString
int main (int argc, string argv[])
{
char* input = argv[1];
char first[4];
char second[5];
strncpy(first, input, 3);
strncpy(second, input + 3, 4);
first[3] = second[4] = '\0';
}
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv[])
{
if(argc >= 2)
{
const int len = strlen(argv[1]) / 2;
char str1[len + 2], str2[len + 2];
snprintf(str1, len + 1, "%s", argv[1]);
snprintf(str2, len + 2, "%s", argv[1] + len);
printf("1: %s\n2: %s\n", str1, str2);
}
return 0;
}

Tokenized string of char to ints using atoi

I am trying to take user input: (1 345 44 23) and make it into a tokenized char string then into ints. Surprisingly I could not find much help for what I would think would be a common task.
Any ideas how to convert the char string into an in string using tokens?
My program crashes when it gets to the conversion (after the tokenization [I realize this is not a word]).
Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define StrSZE 81
void strInput (char str[], int maxChars);
void custatoi(char * tokenArray[], int * data, int numOfTok);
int main(int argc, char *argv[])
{
char str[StrSZE];
char* tokenArray;
int maxChars=StrSZE-1, cont=1, numOfToken=0, i=0;
int* data;
strInput(str, maxChars);
tokenArray = strtok(str, " \t");
while (tokenArray)
{
printf("token: %s\n", tokenArray);
tokenArray = strtok(NULL, " \t");
numOfToken++;
}
data = (int *) malloc(numOfToken * sizeof(int));
custatoi(tokenArray, data, numOfToken);
system("PAUSE");
return 0;
}
void strInput (char str[], int maxChars)
{
char garbage;
int k=0;
str[0]='\0';
printf("Please type a string of whole numbers (intigers).\n\n");
while ((k<80) && ((str[k] = getchar()) != '\n'))
k++;
/* Clears the keyboard buffer. */
if (k==80)
while((garbage = getchar()) != '\n')
;
/* Place null at the end of the line read in from user */
str[k]='\0';
printf("str after input is: %s\n\n", str);
}
void custatoi(char * tokenArray[], int * data, int numOfTok)
{
int i;
for (i=0; i < numOfTok; i++)
data[i] = atoi(tokenArray[i]);
}
I corrected the errors in yours code: There was some mistakes in main(), tokenArray data type was not correct.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define StrSZE 81
void strInput (char str[], int maxChars);
void custatoi(char* tokenArray[], int * data, int numOfTok);
int main(int argc, char *argv[])
{
char str[StrSZE];
int maxChars=StrSZE-1, cont=1, numOfToken=0, i=0;
int* data;
char* tokenArray[50]; // Declared correctly
strInput(str, maxChars);
tokenArray[i] = strtok(str, " \t"); // Also made a change here!
while (tokenArray[i])
{
printf("token: %s\n", tokenArray[i]);
i++;
tokenArray[i] = strtok(NULL, " \t");
numOfToken++;
}
data = (int *) malloc(numOfToken * sizeof(int));
custatoi(tokenArray, data, numOfToken);
printf("data\n");
for(i=0;i<numOfToken;i++){
printf(" %d\n",data[i]);
}
system("PAUSE");
return 0;
}
void strInput (char str[], int maxChars)
{
char garbage;
int k=0;
str[0]='\0';
printf("Please type a string of whole numbers (intigers).\n\n");
while ((k<80) && ((str[k] = getchar()) != '\n'))
k++;
/* Clears the keyboard buffer. */
if (k==80)
while((garbage = getchar()) != '\n')
;
/* Place null at the end of the line read in from user */
str[k]='\0';
printf("str after input is: %s\n\n", str);
}
void custatoi(char* tokenArray[], int * data, int numOfTok)
{
int i;
for (i=0; i < numOfTok; i++)
data[i] = atoi(tokenArray[i]);
}
At the end of the strtok loop, tokenArray will be set to NULL. You then pass it to custatoi, which presumably crashes when it tries to dereference it.
Note that tokenArray is not an array of strings; it's just a single string pointer (or a pointer to an array of characters). If you want to accumulate the tokens into an array, you'll have to create a separate array for that purpose.
The main problem is that custatoi() expects to work with an array of pointers to char, while tokenArray in main() is a mere pointer to char. The original code never collects all pointers to tokens in the input string into an array that custatoi() expects, there isn't such an array in the original code.
Please study the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define StrSZE 81
void custatoi(char* tokenArray[], int* data, int numOfTok);
int main(void)
{
char str[StrSZE];
char** tokenArray;
int numOfToken = 0, i;
int* data;
//strInput(str, maxChars);
strcpy(str, "1 345 44 23");
tokenArray = malloc(sizeof(char*));
tokenArray[numOfToken] = strtok(str, " \t");
while (tokenArray[numOfToken] != NULL)
{
printf("token: %s\n", tokenArray[numOfToken]);
numOfToken++;
tokenArray = realloc(tokenArray, sizeof(char*) * (numOfToken + 1));
tokenArray[numOfToken] = strtok(NULL, " \t");
}
data = malloc(numOfToken * sizeof(int));
custatoi(tokenArray, data, numOfToken);
for (i = 0; i < numOfToken; i++)
printf("data[%d]=%d\n", i, data[i]);
return 0;
}
void custatoi(char* tokenArray[], int* data, int numOfTok)
{
int i;
for (i=0; i < numOfTok; i++)
data[i] = atoi(tokenArray[i]);
}
Output (idone):
token: 1
token: 345
token: 44
token: 23
data[0]=1
data[1]=345
data[2]=44
data[3]=23

Resources