tadm123 tadm123 - 10 months ago 50
C Question

Using sscanf() function to read a string

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: ");
printf("Enter shift amount (1-25): ");

printf("Encrypted message: ");

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

return 0;


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

(Program is stucked there in an infite loop)

Answer Source

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;