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

int main(int argc, string argv[])
{
if ( argc > 1 || argc < 1 )
    return 1;
else
{
    string s = argv[2];
    int key = atoi(s);

    string text = GetString();

    for (int i= 0, j = strlen(text); i<j; i++)
    {
     if ( isalpha(text[i]) )            //Is it alphabet
     {
         if (isupper(text[i]))          //Is it uppercase
         {
             int letter = text[i];
             int ascii = (letter + key);
             if (ascii <= 90)
                printf("%c", ascii);
            else
            {
               int ascii_a =  ascii % 26;
               printf("%c", ascii_a);
            }
         }
         else                           //Is lowercase
         {
             int letter = text[i];
             int ascii = (letter + key);
             if (ascii <= 122)
                printf("%c", ascii);
            else
            {
                int ascii_a = ascii % 26;
                printf("%c", ascii_a);
            }
         }
     }
     else                                   //not alphabet
     {
        printf("%d", text[i]);
     }
    }
    printf("\n");
    return 0;
}
}
3

It will. If you do not supply any command line arguments. Try it.

Why is that? Recall from Week 2 > Section > Command Line Arguments

enter image description here

argc will always be at least 1, the name of the program.

When is this line if ( argc > 1 || argc < 1 ) false (and thus take the else branch)? If and only if argc = 1.

Addendum I see from this post that you changed if ( argc > 2 || argc < 2 ) to this if ( argc > 1 || argc < 1 ). The former is technically correct (although if (argc != 2) may be clearer to us humans). The seg fault was always coming here string s = argv[2]; (or maybe the next line). Why? If an array has 2 elements, how do you "address" them? array[0] and array[1]. So if argc is 2, which argv is your command line argument?

From the same Section (Slides):

The first element of argv is always found at argv[0]. The last element of argv is always found at argv[argc-1].

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .