#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 30
int main()
{ char c, y, input[N];
int X, i=0, j;
printf("Give displacement\n");
scanf("%d",&X);
printf("Give chars\n");
while(((c=getchar()) !=EOF) && (i<N-1)){
input[i]=c;
i++;
}
input[i]='\0';
j=0;
for(j=0; j<=i-1; j++){
if (isalpha(input[j])){
if (isupper(input[j]))
y=(input[j]-'A'+X)%26+'A';
else
y=(input[j]-'a'+X)%26+'A';
putchar(y);
}
}
return 0;
}
hey all. well, this code doesnt seems to works as it should. It skips 2 positions at the table instead of one. Which makes the program unusable since i need a table of 30 positions. I think that the problem is in the while loop, but i really cant find it. Any help would be apprecieted. Thanks in advance.
After the call to scanf
, there's a newline left in the input buffer. That newline becomes the first character read by getchar
.
To get the newline out of the buffer, add a separate call to getchar
right after the scanf
call:
scanf("%d",&X);
getchar();
That will give you the additional character you're missing.
Also, as mentioned in the comments, c
should be defined as an int
instead of a char
, because getchar
returns an int
. Otherwise, the test for EOF
will always be false.
if you want 30 characters you have to define N as 31
[0 - 29] + '\\0'
In your first while loop i believe that the second test is wrong:
Use it like this:
while(((c=getchar()) !=EOF) && (i<=N-1)){
input[i]=c;
i++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.