Reputation: 43
So, I am coding uppercase function with using pointers. I am trying to make a ERROR message when there is input but unfortunately in terminal I am seeing nothing like s==NULL is not working very well I cant see any ERROR messages.
Probably problem about argument types and pointer but I don't real seeing it!
If my Program Arguments like this:
"Hello 123dsd" "teSting"
Output is:
HELLO 123DSD
TESTING
If my program arguments is blank:
output is nothing:
I want to show ERROR message if arguments are empty like:
Please insert a string!
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#define MAGIC_NUMBER 32
char *uppercase(char *s)
{
if (s == NULL)
{
printf("Please insert a string!");
return 0; //Not working!!
}
else
{
for(char *p = s; *p!=0; ++p)
{
if ('a' <= *p && *p <= 'z')
*p = *p - MAGIC_NUMBER;
}
return s;
}
}
int main(int argc, char *argv[])
{
for(int i=1; i < argc; i++)
{
printf("%s \n", uppercase(argv[i]));
}
return 0;
}
Upvotes: 0
Views: 264
Reputation: 9855
If you call your program without arguments, it doesn't print anything because the loop will not call printf
or uppercase
since argc
will have the value 1
.
You have to add code to main
to handle this case.
int main(int argc, char *argv[])
{
if(argc < 2)
{
fprintf(stderr, "Please insert a string!\n")
return 1;
}
for(int i=1; i < argc; i++)
{
printf("%s \n", uppercase(argv[i]));
}
return 0;
}
Note that I use fprintf(stderr, ...)
for the error message because error messages should not be mixed with normal output.
Upvotes: 1
Reputation: 223699
If you don't enter any parameters to the program, argc
will be 1 so the for
loop in the main
function is never entered. This also means that a NULL pointer will never be passed to uppercase
.
You need to move the check for missing arguments to main
:
int main(int argc, char *argv[])
{
if (argc == 1) {
printf("Please insert a string!");
return 1;
}
for(int i=1; i < argc; i++)
{
printf("%s \n", uppercase(argv[i]));
}
return 0;
}
Upvotes: 1