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 › Convert data type of key variable from string type to int type
- This topic is empty.
-
AuthorPosts
-
February 1, 2022 at 5:30 am #180
[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”]
#include<stdio.h> #include<cs50.h> #include<ctype.h> #include<string.h> #include<stdlib.h> int main(int argc, string argv[]) { string enteredtext = argv[2]; printf("Entered text by user: %s\n", enteredtext); int n = strlen(enteredtext); printf("length of entered text: %i\n", n); string key = argv[1]; atoi(key); for (int i = 0; i < n; i++) { if (isupper(enteredtext[i]))//if (isupper(name[i])) { enteredtext[i] = ((((enteredtext[i] - 65) + key)%26) + 65);//newuppercase_array[i] = ((((enteredtext[i] - 65) + key)%26) + 65); } else if (islower(enteredtext[i])) { enteredtext[i] = ((((enteredtext[i] - 97) + key)%26) + 97);//newuppercase_array[i] = ((((enteredtext[i] - 97) + key)%26) + 97); } else { enteredtext[i] = enteredtext[i]; //newuppercase_array[i] = enteredtext[i]; } printf("%c",enteredtext[i]);// printf("%c",newuppercase_array[i]); } printf("\n"); }
[/dm_code_snippet]
The goal is to convert data type of key variable from string type to int type so that from command line interface, key is string type, but for computing from plain text to cipher text, key is converted to data type int.
I tried in the above code wtih:
atoi(key);
Also tried with
atoi(argv[1])
Both did not compile. Seeking help as it appears my concept is not clear.
Reply
You can’t change the data type of a variable in C.
atoi
is a function that takes in a string and returns the equivalent number. You need to store that return value in a new variable of the correct type:[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 shift = atoi(argv[1]);
[/dm_code_snippet]
Query
Can it be:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”yes” line-numbers=”yes” bg-color=”#abb8c3″ theme=”dark” language=”clike” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
int shift = atoi(enteredtext);
[/dm_code_snippet]
It is confusing.
Reply
Is
enteredtext
a string containing a number that you want to convert to an actual number?[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.