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 › How to make sure that two inputs are only entered by the user or program reprompts
Tagged: Caesar project
- This topic is empty.
-
AuthorPosts
-
February 5, 2022 at 7:25 am #194
Array argv[] will be of length 2.
argv[0] that will hold ./caesar.c
argv[1] will contain the key value
So to begin with, I perhaps need to check if indeed two inputs are entered by the user.
Here is the code I tried:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”yes” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
int main(int argc, string argv[]) { if (argv[]!=2) { printf("enter key value"); return 0; } ............ }
[/dm_code_snippet]
Fail to figure out what is wrong with the above code.
Will it be:
[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 main(int argc, string argv[]) { if (int argv[]!=2) { printf("enter key value"); return 0; } ............ }
[/dm_code_snippet]
The above code too appears faulty.
Reply
argv, as you stated, holds the input parameters, so what you want to do is check if the length of argv is different from two, not if argv itself is different from two. Luckily, the other parameter argc denotes this value – it corresponds to the amount of arguments provided. So try checking if argc =! 2 instead 🙂
Query
Out of curiosity or for the sake of learning, is it possible to check if indeed two parameters with argv[] on that line.
Reply
You could try error handling with a try and catch. Not something I’m that experienced with. But seems like something to use if you try accessing a third value in an array when there’s only two.
I would just use argc[] since it’s already known.
Yes, the number of parameters corresponds to the length of argv, so you can check if the length of argv =! 2
Number of inputs is stored in argc. Thus to limit the number of inputs, you gotta tweak with argc and not argv[]
https://edstem.org/us/courses/176/discussion/1094835
[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.