Im trying make a program print a specific output using a enviroment variable in the command line, but the program seems to be stuck on my first input.
Here's my code
#include <stdio.h>
#include <stdlib.h>
void print_data(char*select);
int main (int argc, char * argv[]){
int ret;
char *ch = NULL;
if( argc == 2)
{
ch = argv[1];
}
else
{
ch = getenv("V1");
}
void print_data(ch);
return 0;
}
void print_data(char* select){
if(select, "k")
{
printf("Value set to key\n");
}
else if(select, "l")
{
printf("Value set to last name\n");
}
else if (select, " ")
{
printf("Value set to %s\n", select);
}
}
My problem is that the program either only prints "Value set to key" or "Value set to last name". How can I use the pointer in Print_data to check what command is entered in the command line?
if(select, "k")
is almost certainly not doing what you want, but it is not entirely clear what it is that you want. That expression is equivalent to if(1)
, which is why you get the behavior you see. Perhaps you intend:
if( select[0] == 'k' ) ...
else if( select[0] == 'l' ) ...
else if( select[0] == ' ' ) ...
which would be better written:
switch( select[0] ) {
case 'k': ...;
...
There is also a problem with
void print_data(ch);
insidemain
Thanks, that helped. But would "select" be the default invironment variable when I dont have any input?
What's the problem in main?
@B0ris If argc != 2, then select will be the result of
getenv
, which may be NULL, in which caseselect[0]
will (almost certainly) lead to a segmentation fault.@B0ris
void print_data(ch);
should beprint_data(ch);
or(void)print_data(ch);
(not necessary sinceprint_data
already returnvoid
, but legal)