#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, string key[])
{
//check if user typed key arguement
if (argc == 2)
{
//if they did, how many characters are there?
while (strlen(key[1]) != 26)
{
printf("Key must contain 26 characters\n");
return 1;
}
return 0;
***//Make sure the characters are letters
int n = strlen(key[1]), i;
string k = key[1];
for (i = 0; i < n; i )
{
if (!isalpha(k[i]))
{
printf("Key must contain only alphabetical characters\n");
return 1;
}
}***
}
//if they did not type or type more than one argument reply the following:
else if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
return 0;
}
So, I've made it up the program printing errors when the user types too many characters and too many arguments/too few arguments. But when I try typing with numbers, it won't print the error. I'm not sure if I simply didn't write the appropriate code that will go through each character and check. Any direction would be appreciated. It also doesn't print any other error, the program just runs normally as if I didn't put a number in there.
CodePudding user response:
You have a redundant return statement
while (strlen(key[1]) != 26)
{
printf("Key must contain 26 characters\n");
return 1;
}
return 0;
^^^^^^^^^
Just write
if ( strlen(key[1]) != 26 )
{
printf("Key must contain 26 characters\n");
return 1;
}
Also instead of else if
else if (argc != 2)
{
//...
it is enough to write
else
{
//...
CodePudding user response:
Immediately after you check that the second argument is 26 characters long, you return 0;
stopping any further execution.
Further, I strongly suggest you do all of your error checking up front. This cleans up the code considerably.
int main(int argc, string key[])
{
if (argc != 2) {
printf("Usage: ./substitution key\n");
return 1;
}
if (strlen(key[1] != 26) {
printf("Key must contain 26 characters\n");
return 1;
}
//Make sure the characters are letters
int n = strlen(key[1]), i;
string k = key[1];
for (i = 0; i < n; i )
{
if (!isalpha(k[i]))
{
printf("Key must contain only alphabetical characters\n");
return 1;
}
}
return 0;
}
And remember that a while loop that returns on its first iteration if just a misleading way to write if
.
while (A) {
return B;
}
Is doing the same thing as:
if (A) {
return B;
}