0

I know I can use printf to directly print it out, however, if I wanted to store it into the string cipher and then print that out is it possible?

int main(int argc, string argv[])
{
   if (argc != 2){
    printf("error\n");
    return 1;
}

if (atoi(argv[1])  <  0){
    printf("error\n");
    return 1;
}

 string s = NULL;

do {
  printf("Plain Text\n");
 s = get_string();

}while (s == NULL);

int k = atoi(argv[1]);
string cipher = NULL;


for( int i = 0, n = strlen(s); i < n; i++){

      if(isalpha(s[i]))
         if(islower(s[i]))
        {
         cipher[i] =  ((((s[i] - 97)+k)%26)+97);
        }
        if(isupper(s[i]))
        {
            cipher[i] =  ((((s[i] - 65)+k)%26)+65);
        }

    else
    {
        cipher[i] =  s[i];
    }
}
printf("Cipher text: %s\n", cipher);
return 0;  

}

3
  • It is possible as your code does exactly what you ask about. it stores into the string cipher and then print it out. Or I misunderstand the question?
    – obesman
    Jul 11, 2017 at 7:11
  • Thanks for answering. That is what I want it to do however it gives me a segmentation fault when I run it. When i switch the cipher[i] with printf, it works perfectly.
    – Ryan A
    Jul 12, 2017 at 2:25
  • Sorry, should have examined your code before commenting. The answer follows.
    – obesman
    Jul 12, 2017 at 5:38

1 Answer 1

2

Yes it is possible, however, string var are a bit tricky thing implemented by cs50. In coming weeks you will see why, so I won't explain it here in details, just show one of the solutions.

You initialize both s and cipher with NULL. Its fine for s as then you reinitialize it with get_string(). But not for cipher. It remains NULL so any attempt to write in it results in Segm fault.

To deal with that, you may instead declare an array of chars with size equals to length of s + 1

char cipher[strlen(s) + 1]; 

plus 1 because you need this cell to put '\0' there which indicates end of string. Then,

printf("Cipher text: %s\n", cipher);

will work.

Also, there are a few other deficiencies in your code.

  1. atoi(argv[1]) will always return 0. atoi tries to convert ASCII codes of digits into digits. If there is no digit, it returns 0. so atoi("11") == 11, atoi ("aa") == 0.

  2. Seems you are confused a bit with } brackets in "if" conditions. As a result, cipher[i] = s[i] in the end of the loop works when it shouldn't overwriting your efforts.

0

You must log in to answer this question.

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