我试着弄清楚为什么这个程序不能工作。它将小写转换为大写,假设我输入" K ",它返回K。然后我继续输入"A",它不返回"a",但退出。但是为什么呢?代码如下:
#include <stdio.h>
#include <stdlib.h>
int main(){
char UPPER,LOWER;
printf("Enter UPPERCASE\n");
UPPER = getchar();
if (UPPER >= 65 && UPPER <= 90)
{
UPPER = UPPER + 32;
printf("The UPPERCASE now is %c\n", UPPER);
}
printf("Enter lowercase\n");
LOWER = getchar();
if (LOWER >= 97 && LOWER <= 122)
{
LOWER = LOWER - 32;
printf("The lowercase now is %c\n", LOWER);
}
getchar();
getchar();
}发布于 2014-07-08 14:57:57
如果编译并运行以下代码:
void main(void)
{
char c = getchar();
printf("c = %d %c\n", c, c);
c = getchar();
printf("c = %d %c\n", c, c);
}您将看到以下输出:
user@host ~/work/tmp $ ./test
a
c = 97 a
c = 10
/* new line there*/这段代码并不相同,但可以工作:
#include <stdlib.h>
#include <stdio.h>
#define BUFSIZE 4
int main(void)
{
char UPPER[BUFSIZE] = {0}, LOWER[BUFSIZE] = {0};
int i;
printf("Enter UPPERCASE\n");
fgets(UPPER, BUFSIZE, stdin);
for(i = 0; i < BUFSIZE; i++)
{
if (UPPER[i] >= 65 && UPPER[i] <= 90)
{
UPPER[i] = UPPER[i] + 32;
}
}
printf("The UPPERCASE now is %s", UPPER);
printf("Enter LOWERCASE\n");
fgets(LOWER, BUFSIZE, stdin);
for(i = 0; i < BUFSIZE; i++)
{
if (LOWER[i] >= 97 && LOWER[i] <= 122)
{
LOWER[i] = LOWER[i] - 32;
}
}
printf("The LOWERCASE now is %s", LOWER);
return 0;
}发布于 2014-07-08 15:06:24
您应该分别在printf("The UPPERCASE now is %c\n", UPPER);之后添加getchar();,并在printf("The lowercase now is %c\n", LOWER);之后再次添加。大部分程序都以getch()结尾,因此我们认为getch()用于显示output...but,而wrong.It用于从控制台获取单个字符。正确的代码应该如下所示:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char UPPER, LOWER;
printf("Enter UPPERCASE\n");
UPPER = getchar();
if (UPPER >= 65 && UPPER <= 90)
{
UPPER = UPPER + 32;
printf("The UPPERCASE now is %c\n", UPPER);
}
getchar();
printf("Enter lowercase\n");
LOWER = getchar();
if (LOWER >= 97 && LOWER <= 122)
{
LOWER = LOWER - 32;
printf("The lowercase now is %c\n", LOWER);
}
getchar();
}https://stackoverflow.com/questions/24625187
复制相似问题