简体   繁体   English

带有表 C 的 while 循环

[英]While loop with tables C

#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.它跳过桌子上的 2 个位置而不是一个。 Which makes the program unusable since i need a table of 30 positions.这使程序无法使用,因为我需要一个包含 30 个位置的表。 I think that the problem is in the while loop, but i really cant find it.我认为问题出在while循环中,但我真的找不到。 Any help would be apprecieted.任何帮助将不胜感激。 Thanks in advance.提前致谢。

After the call to scanf , there's a newline left in the input buffer.在调用scanf ,输入缓冲区中还剩下一个换行符。 That newline becomes the first character read by getchar .该换行符成为getchar读取的第一个字符。

To get the newline out of the buffer, add a separate call to getchar right after the scanf call:要从缓冲区中取出换行符,请在scanf调用后立即添加对getchar的单独调用:

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 .此外,如评论中所述, c应定义为int而不是char ,因为getchar返回int Otherwise, the test for EOF will always be false.否则, EOF的测试将始终为假。

if you want 30 characters you have to define N as 31如果你想要 30 个字符,你必须将 N 定义为 31

[0 - 29] + '\\0' [0 - 29] + '\\0'

In your first while loop i believe that the second test is wrong:在您的第一个 while 循环中,我认为第二个测试是错误的:

Use it like this:像这样使用它:

while(((c=getchar()) !=EOF) && (i<=N-1)){
    input[i]=c;
    i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM