Hello everyone,
I'm following along with a Harvard Course (by myself, I'm not an enrolled student) over at This is CS50 / OpenCourseWare . Again, this is not graded work.
An assignment in pset2 is to create a program that takes a command like input for a key and then rotates all characters in an input string by that amount of places. The key can be longer than 26, it needs to wrap around (so 30 for instance is the same as 4, in other words key % 26). If the key is not a positive int then it should exit.
Secondly, it needs to preserve case and ignore any non alphanumerical chars.
CS50 provide their own lib that allows you to use GetInput functions and a few types such as string instead of char *. These training wheels will be taken off eventually but not now.
I have managed to create the program and it works fine except for one problem. It converts non caps to caps. I've looked at this code for hours and I even posted the relevant code on the cs50 discussion group but to no avail. Does anyone have a clue on what I might had messed up?
To reiterate the problem. if I tell it to rotate by 1 with the input of Aa Yy Zz, it gives me BB ZZ AA instead of Bb Zz Aa.
The code isn't fully cleaned up yet, the commented out parts are used as diagnostics.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>
#define KEY 1
int
main(int argc, char *argv[])
{
char c;
int key = atoi(argv[KEY]), i, n;
string s;
//printf("%d\n", key);
//checks for key as pos int &
//that there is one command line arg
if(key > 0 && argc == 2)
{
// printf("key: %d\n", key);
// printf("count: %d\n", argc);
// gets user input.
s = GetString();
printf("%s\n", s);
//checks for valid string
if(s != NULL)
{
for(i = 0, n = strlen(s); i < n; i++) // starts encoding
{ // checks for alphabetical non digit char
if (s[i] >= 'A' && s[i] <= 'Z')
printf("%c", (((s[i] - 'A') + key) % 26) + 'A'); // rotates
else if (s[i] >= 'a' && s[i] <= 'z')
printf("%c", (((s[i] - 'a') + key) % 26) + 'a');
else
printf("%c", s[i]); // non alphabet char preserved
}
printf("\n");
return 0; // return success
}
}
else
return 1; // return failure.
}
I hope I'm not breaking any rules here.