Caesar cipher help! #172203
Replies: 4 comments
-
Both your "return 1;" statements are outside their respective if statements. So regardless of whether or not your if condition is met, the return will execute. Move them both inside and it should work. Also add a "return 0;" at the end of the main function since a successful program should do that. |
Beta Was this translation helpful? Give feedback.
-
Hey @GillianG2203, You should only return 1; inside the error cases, not after. Only exit if the input is invalid. #include <ctype.h> int main(int argc, string argv[])
} |
Beta Was this translation helpful? Give feedback.
-
here is my take : Move the if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
for (int i = 0; i < strlen(argv[1]); i++)
{
if (!isdigit(argv[1][i]))
{
printf("Usage: ./caesar key\n");
return 1;
}
} With this change, the program will only exit when there’s an error and otherwise will proceed to: int k = atoi(argv[1]);
string plaintext = get_string("Plaintext: "); after this fix, the program should correctly prompt for plaintext input and then perform the Caesar cipher encryption |
Beta Was this translation helpful? Give feedback.
-
Code Comparison: Caesar Cipher
Original Code (Incorrect)
In this snippet, the return 1; is outside the if block. This means that, regardless of the value of argc, the program will print the message (if necessary) and then stop when it reaches return 1;. It never had the chance to ask the user for the text. Corrected Code
In the corrected version, the return 1; is inside the if block. Now, the program will only stop if the condition (argc != 2) is true. If the condition is false (meaning the number of arguments is correct), the program ignores the if block and continues its execution normally. The same error and the same correction were applied in the validation to check if the key contains only digits.
Original Code (Missing) Corrected Code
Original Code Corrected Code The math.h library was not being used anywhere in the program, so it was not necessary to include it. It is advisable to include only the libraries that are actually needed. Summary |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Body
I am working on the cs50 problem set 2 and have run into an issue with my caesar ciper problem. Everything is working, as in it will make the program without errors, but after imputing a number on the command line, the user should be prompted for text. My code is not prompting for text. Please help! I'm not sure what I'm missing.
#include <ctype.h>
#include <cs50.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./caesar key\n");
}
return 1;
}
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions