Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“putchar”的以下两种用法有什么区别?_C_If Statement_Switch Statement_Getchar_Putchar - Fatal编程技术网

“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