gpt4 book ai didi

c - 如何删除C程序中的重复输出?

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:23 24 4
gpt4 key购买 nike

我创建了一个从用户输入中获取字符的程序。它将字母转换为大写并将其显示给最终用户。

但是,我收到了一个输出问题,我得到了双倍的“请输入小写字符:”和下面的额外一行。我不太确定是什么原因造成的,但这是我目前的程序:

#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>

// Converts lowercase letter to uppercase

int main()
{
bool continue_program = true;

printf("Program Running \n");
int lower, upper;
while (continue_program){
printf("Please enter a character in lower case:");
printf("\n");
int lower = getchar();
if(lower=='q' || lower=='Q'){
printf("Goodbye \n");
break;
} else {
upper = toupper(lower);
putchar(upper);
printf("\n");
}
}
return 0;
}

输出示例:

./a.out
Program Running
Please enter a character in lower case:
a
A
Please enter a character in lower case:


Please enter a character in lower case:
b
B
Please enter a character in lower case:


Please enter a character in lower case:
p
P
Please enter a character in lower case:


Please enter a character in lower case:
Q
Goodbye

最佳答案

只要改变这个:

int lower, upper;

到:

char lower, upper;

还有这个:

int lower = getchar();

到:

scanf(" %c", &lower);
//^ Space which 'eats' remaning '\n' in the buffer

关于c - 如何删除C程序中的重复输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com