IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 2: [Arrays] – Functions, Variable and Scope, Debugging, Arrays, and Command Line Arguments › Making sure if entered key by user is indeed integer
Tagged: arrays, Caesar project
- This topic is empty.
-
AuthorPosts
-
February 6, 2022 at 10:08 am #199
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”yes” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
#include<stdio.h> #include<cs50.h> #include<ctype.h> #include<string.h> #include<stdlib.h> int main(int argc, string argv[]) { if (argc!=2) { printf("enter key value"); return 0; } string enteredtext = get_string("plain text:"); printf("Entered text by user: %s\n", enteredtext); int n = strlen(enteredtext); printf("length of entered text: %i\n", n); string key = argv[1]; int keylen = strlen(key); int counter = 0; while(counter !> argv[1][keylen]) { if(isalpha (argv[1][0])); { printf("key value should be integer"); return 0; } else { counter = counter + 1; } } int convertedkey = atoi(argv[1]); for (int i = 0; i < n; i++) { if (isupper(enteredtext[i])) { enteredtext[i] = ((((enteredtext[i] - 65) + convertedkey)%26) + 65); } else if (islower(enteredtext[i])) { enteredtext[i] = ((((enteredtext[i] - 97) + convertedkey)%26) + 97); } else { enteredtext[i] = enteredtext[i]; } printf("%c", enteredtext[i]); } printf("\n"); }
[/dm_code_snippet]
Any clue appreciated particularly for:
[dm_code_snippet background=”yes” background-mobile=”no” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
int counter = 0; while(counter !> argv[1][keylen]) { if(isalpha (argv[1][0])); { printf("key value should be integer"); return 0; } else { counter = counter + 1; } }
[/dm_code_snippet]
Reply
int counter = 0; //counter is initialized as 0.
while(counter !> argv[1][keylen]) while loop supposedly runs until when? should be like while(counter < keylen)
{
if(isalpha (argv[1][0])); //argv[1][0]. Only checks the first char of argv[1] string. should be something like argv[1][counter]
{
printf(“key value should be integer”);
return 0;
}
else
{
counter = counter + 1;
}
}
There might be more issues but for now let you get through these.
In this case OP only checks if the key contains alpha characters. What he should check is if the key contains anything else than digits. The function isdigit() is useful for this.
Exactly what I realized when I was doing the same problem and went into sea of punctuations.
[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.