“putchar”的以下两种用法有什么区别?
我在写一些代码时,程序的一部分出现了意外的输出,这反过来又破坏了整个系统 代码可以简化并缩短为:“putchar”的以下两种用法有什么区别?,c,if-statement,switch-statement,getchar,putchar,C,If Statement,Switch Statement,Getchar,Putchar,我在写一些代码时,程序的一部分出现了意外的输出,这反过来又破坏了整个系统 代码可以简化并缩短为: char ch; printf("Enter Number: "); while ((ch = getchar()) != '\n') { if (ch >= 65 && ch <= 67) { ch = 2; } putchar(ch); } 实际产量 一旦遇到这个问题,我决定调整一些东西,并提出了下面的代码,它工作得非常好。它
char ch;
printf("Enter Number: ");
while ((ch = getchar()) != '\n') {
if (ch >= 65 && ch <= 67) {
ch = 2;
}
putchar(ch);
}
实际产量
一旦遇到这个问题,我决定调整一些东西,并提出了下面的代码,它工作得非常好。它使用相同的方法,但产生不同的输出:
char input;
printf("\nEnter Number: ");
while ((ch = getchar()) != '\n') {
switch (toupper(ch)) { //toupper function not really needed since I am expecting the user to enter upper-case letters ONLY
case 'A': case 'B': case 'C':
printf("2");
break;
default:
putchar(ch);
}
}
预期产量
实际产量
我无法理解为什么无法将第一个代码中输入的字符的ASCII值转换为单个整数。产出差异的原因是什么?我只是将控制表达式的类型从
if语句
更改为switch语句
(或者我认为是这样)。如何更改第一个代码以提供与第二个代码相同的输出?在第一个版本中,设置ch=2
使ch
成为ASCII值为2的字符,而不是2
字符<代码>ch=0x32代码>在您的第一个版本中可能会起作用,因为ASCII 50=0x32是字符2
。更简单的方法是ch='2'代码>
在第二个版本中,您使用的是printf(“2”)
。因此,编译器在处理字符串“2”
时为您生成ASCII值,就像处理ch='2'时一样代码>。尝试printf(“%d\n”和“2”)你应该看到50
ch=2代码>-->ch='2'
,并且getchar()
的结果是一个int
(不是char
)不要使用幻数!'A'
而不是65
等是否太清晰?请不要使用假定字符编码方式的幻数。您最初引用的Keine Lust使用的是'2'
而不是0x32
。
Enter Number: 23-AB
23-☺☺
char input;
printf("\nEnter Number: ");
while ((ch = getchar()) != '\n') {
switch (toupper(ch)) { //toupper function not really needed since I am expecting the user to enter upper-case letters ONLY
case 'A': case 'B': case 'C':
printf("2");
break;
default:
putchar(ch);
}
}
Enter Number: 23-AB
23-22
Enter Number: 23-AB
23-22