我的程序看不到while循环,我无法输入c变量
我想输入一个字符串。如果此字符串中的char是数字,则他将保留为数字;如果不是数字,则将在ascii代码中更远地移到char'num'位置。
#include <stdio.h>
#include <ctype.h>
int main()
{
int num;
char c;
printf("Enter number: \n");
scanf("%d", &num);
printf("Enter a string : \n");
while ((c = getchar()) != '\n')
{
if (isdigit(c))
{
putchar(c);
}
else
{
putchar(c + num);
}
}
return 0;
}
使用scanf()
和时getchar()
,通常必须在所需的键之后按[返回]键。通常,所需的键和返回键都放置在stdin流中。问题代码忽略了这一点。因此,第一个所需的密钥被读取scanf()
并存储在中num
,但返回键仍'\n'
留在缓冲区中。后来由读取getchar()
并存储在中c
。因此,满足了循环退出标准,并且程序终止了。
要使代码正常工作,必须以某种方式读取'\n'
调用scanf();
或可能还留下的不需要的返回键getchar()
。
也许像这样:
#include <stdio.h>
#include <ctype.h>
int main()
{
int num;
int c;
char cr[2];
printf("Enter number: \n");
scanf("%d%1[\n]", &num, cr); // Reads %d into num, and garbage '\n' into cr.
printf("Enter a string : \n");
while((c = getchar()) != '\n')
{
if(isdigit(c))
putchar(c);
else
putchar(c + num);
getchar(); // Reads garbage '\n' from previous getchar()
}
printf("\n");
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句