1

I have created following C code for encrypt words.(caesar cipher) when I run this it prints U at the end always.if you run this you will see it.

#include<stdio.h>

int main(void){
    int x;
    char en[100];

    fgets(en,100,stdin);
    for(x=0;x<100;x++){
        if(en[x]=='\0'){
            break;
        }
        en[x]=((en[x]-71-3)%26)+97;
    }
    printf("%s\n",en);
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
migara
  • 19
  • 3

2 Answers2

6

fgets places a '\n' character before the '\0' at the end of the buffer. So if you don't want to encrypt it, loop until the condition below is satisfied:

if (en[x] == '\0' || en[x] == '\n') break;

To be rigorous, the actual reason why you are getting a U is due to the fact that \n has ASCII code 10. Thus, (10-74)%26 + 97 = 85, which is the ASCII code for U.

Claudi
  • 5,224
  • 17
  • 30
  • 4
    Loop while `x<99` won't help if the string is shorter than that. – interjay Sep 14 '14 at 17:26
  • ohhhhh thank you very much.i have been suffering from this problem for 6 hours.i have a another qs.i thought fgets places '\0' at the end like scanf.why is that wrong? – migara Sep 14 '14 at 17:39
  • Actually fgets terminates the buffer with \n\0. See http://linux.die.net/man/3/fgets – Claudi Sep 14 '14 at 17:53
0
if (en[x] == '\0' || en[x] == '\n') break;

The above condition should solve your problem. some reading for the \0 and \n is given in the following link

he is a output of the "trail" run which give more insight on a step by step way

trial

*rial
rial
q(ial
qial
qoal
qoal
qofl
qofl
qofx"
qofx
qofxi?
qofxi?
qofxiU
Community
  • 1
  • 1
akrv
  • 55
  • 11
  • I thought fgets places '\0' at the end like scanf.why is that wrong? – migara Sep 14 '14 at 17:53
  • `fgets` puts the values in the buffer until the you press enter for example: if you type in `trial` for `stdin` you press enter which is also returned during `fgets()` but `scanf()` doesn't do that. you might get more idea from this [link](http://stackoverflow.com/questions/14033477/why-is-the-first-string-ignored-when-reading-with-fgets-from-stdin?rq=1) as well – akrv Sep 14 '14 at 17:59