Reputation: 11
Please I'm stuck in this code from an exercise on the CS50 course. I was asked to call the only_digits function on argv[1] as stated below but I don't seem to understand how.
Modify main in such a way that it calls
only_digits
on argv[1]. If that function returns false, then the main should print "Usage: ./caesar key\n" and return 1. Else main should simply return 0.
Here is my code.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool only_digits(string s);
int main(int argc, string argv[])
{
string s = argv[1];
if(argc != 2 && only_digits(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}
else{
return 0;
}
}
bool only_digits(string s)
{
for(int i = 0; i < strlen(s); i++)
{
if(isdigit(s[i]))
{
return true;
}
else{
return false;
}
}
return false;
}
Upvotes: 0
Views: 203
Reputation: 50210
2 errors
if (argc != 2 && only_digits(argv[1]))
you will only issue the error message if argc != 2 and its not all digits, that means if they enter the correct numer of args (1) you will never look at it. You mean
if (argc != 2 || only_digits(argv[1]))
in this
for (int i = 0; i < strlen(s); i++)
{
if (isdigit(s[i]))
{
return true;
}
else {
return false;
}
}
YOu look at the first digit and return true or false, but thats it. YOu have to keep going.
for (int i = 0; i < strlen(s); i++)
{
if (!isdigit(s[i]))
{
return false;
}
}
// if we get here then all are digits
return true;
Upvotes: 1