简体   繁体   中英

What's wrong in my code ? (Vigenere cypher cs50, pset2)

My code for CS50 pset2 Vigenere cypher is as follows. I am new to C programming.

[ I edited the code once after I got some suggestions and this code(below) is my new edited code.]

When I run the code it produces infinite loop and also new encrypted text is not produced as it is supposed to be. Can I please get some suggestions and advice regarding the correction of my code ? Thank you,

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, string argv[])
{
    if (argc != 2)   //if it is not rqual to 2, it gives an error message.
    {
        printf("Enter the valid input : \n");
        return 1;
    }

    if (argc == 2)   //if two commands are given then it proceeds to other step.
    {
        string k =  argv[1];
        string m = GetString();
        int l =  strlen(k);
        int p =  strlen(m);



        for( int i = 0; i <= p ; i++ ) //it has to keep on rotating from 0 to len of string and back to zero and so on.
        {
            {
                i = i % l;
            }   


            if (isalpha(m[i]) && isalpha(k[i]))    // it proceeds ahead only if the input given is an alphabet, if the input is sth other than alphabet it prints exactly as it is.
            {


                for(int t = 0; t <= p ; t++)
                {
                    if(isupper(m[t])) // when is it capital letter.
                    {
                        printf("%c", ( m[t] - 65 + k[i]) % 26 + 65);
                    }
                    if(islower(m[t]))  // when it is small letter.
                    {
                        printf("%c" , ( m[t] - 97 + k[i])% 26 + 97);
                    }

                }

            }


            else //if it is not an alphabet it returns as it is.
            {
                printf("%c",  m[i]);
            }
        }    

    }
        printf("\n");
        return 0;
}

Let's look at the error. It says that the parameter you gave there is not an array, while you are using it as an array. And that's right : p is an integer, and not an array :

int p = strlen(msg);

Using p[i] means that you want to access the element number i of your p array. But it is impossible to reach this value, because p is simply an integer variable, and not an array.

What you probably wanted to use as an array was one of your string parameters, key or msg. A string variable in CS50 is the equivalent of a char * variable in classic C, and is used as an array of characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM