我的代码在 C 中看不到 while 循环(使用 getchar 函数)
My code dont see a whille loop in C (with a getchar function)
我的程序没有看到 while 循环,我无法输入我的搅拌到 c 变量
我想输入一个字符串。如果此字符串中的 char 将是数字,则他将保留为数字,如果他不是数字,他将更改为 char 'num' 放在 更远的地方ascii 码.
#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()
,您通常必须在所需键之后按 [return] 键。所需的密钥和 return 密钥(通常)都放在标准输入流中。问题代码忽略了这一点。因此,第一个想要的密钥被 scanf()
读取并存储在 num
中,但将 return 密钥 '\n'
留在缓冲区中;然后由 getchar()
读取并存储在 c
中。因此满足循环退出条件,程序终止。
不知何故,要发挥作用,代码必须读取不需要的 return 键 '\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;
}
我的程序没有看到 while 循环,我无法输入我的搅拌到 c 变量
我想输入一个字符串。如果此字符串中的 char 将是数字,则他将保留为数字,如果他不是数字,他将更改为 char 'num' 放在 更远的地方ascii 码.
#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()
,您通常必须在所需键之后按 [return] 键。所需的密钥和 return 密钥(通常)都放在标准输入流中。问题代码忽略了这一点。因此,第一个想要的密钥被 scanf()
读取并存储在 num
中,但将 return 密钥 '\n'
留在缓冲区中;然后由 getchar()
读取并存储在 c
中。因此满足循环退出条件,程序终止。
不知何故,要发挥作用,代码必须读取不需要的 return 键 '\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;
}