I'm on the stage where we need to correctly setup the command line argument to take only digits and to break out of the code if the user types anything else other than a digit. (leaving it empty, inputting two digits, inputting text, inputting two pieces of text etc.)
So I made the program work correctly if the user types more than one command line argument or one command line argument which isn't a digit. My problem is that if I leave the command line argument blank the program gives me a segmentation fault and it doesn't work as intended if I type a single command line like "1d". Can anyone tell me where I went wrong? I'm stuck. Here's the code:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
bool only_digits(string argv[]);
int main(int argc, string argv[])
{
bool digits = only_digits(argv);
if(argc != 2 || digits == false)
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
return 0;
}
}
bool only_digits(string argv[])
{
bool digit = false;
for(int i = 0; i < strlen(argv[1]); i )
{
if(isdigit(argv[1][i]))
{
digit = true;
}
}
return digit;
}
CodePudding user response:
You have two problems:
- You're calling
only_digits()
before checking whetherargv[1]
exists. So you get a segfault if there are no command-line arguments. Fix this by callingonly_digits()
after theargc
check. - The condition in
only_digits()
is backwards. It returnstrue
if any character is a digit, but it's supposed to returntrue
only if all the characters are digits.
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
bool only_digits(string argv[]);
int main(int argc, string argv[])
{
if(!(argc == 2 && only_digits(argv)))
{
printf("Usage: ./caesar key\n");
return 1;
}
return 0;
}
bool only_digits(string argv[])
{
for(int i = 0; i < strlen(argv[1]); i )
{
if(!isdigit(argv[1][i]))
{
return false;
}
}
return true;
}