0

I'm a begginer so I'm stuck in this part. I need to type a message, and a shift amount by which letters should be shifted to 'encrypt' a message. The problem is that It's not displaying any text, it just never exits the while loop.

Any help would be greatly appreciated.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{

   char ch,message[50]={0};
   int shift;


   printf("Enter message to be encrypted: ");
   scanf("%s",message);
   printf("Enter shift amount (1-25): ");
   scanf("%d",&shift);

   printf("Encrypted message: ");

   while((sscanf(message," %c",&ch) == 1) && (ch != '\n'));
   {
       ch += shift;
       putchar(ch);
   }

    return 0;
}

Output:

Enter message to be encrypted: abcABC
Enter shift amount (1-25): 3
Encrypted message: 

(Program is stucked there in an infite loop)

tadm123
  • 8,294
  • 7
  • 28
  • 44

2 Answers2

1

You are wrongly using sscanf. It will always read only the first character.

Try this to achieve what you want.

int i=0;
while(i<strlen(message))
{
    ch=message[i++];
    ch += shift;
    putchar(ch);
}
Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
  • I might be mistaken, but is there any reason why you can use 'fscanf' to go through each character on a file but not 'sscanf', which is suppose to do the same thing but for a string? – tadm123 Sep 25 '16 at 04:46
  • @tadm123 `fsacnf` is sued to work with `FILE`S see reference http://www.cplusplus.com/reference/cstdio/fscanf/ . – Coldsteel48 Sep 25 '16 at 04:54
  • I know, that's what I'm saying @user3351949. I thought that using sscanf for a string was equivalent to using fscanf for a file. – tadm123 Sep 25 '16 at 04:55
  • `sscanf` is basically used to retrieve information from a `string` in a specific format. See use of sscanf here : http://www.cplusplus.com/reference/cstdio/sscanf/ – Ravi Shankar Bharti Sep 25 '16 at 04:57
  • 1
    @tadm123 Well it is not, when reading from file, it has a pointer to the place you are reading/writing (don't remember it's name it) and it increments that pointer after you are reading. for string it doesn't have that pointer you should manage it your self. – Coldsteel48 Sep 25 '16 at 04:57
  • I see. My book doesn't really go into lots of detail in how to use sscanf, thanks for the link guys. – tadm123 Sep 25 '16 at 04:59
1

There is couple of things with your code a) you have ";" at the end of your while b) you always reading only the first character inside the sscanf thats why you are in the infinite loop. I would suggest to replace while with the for loop like shown below.

scanf automagically appends'\0' to the end of the string.

int i;
for(i=0 ; i<50 && mesage[i] != '\0'; i++) 
{ 
    ch = message[i]; 
    ch += shift; 
    putchar(ch); 
}
Coldsteel48
  • 3,482
  • 4
  • 26
  • 43