如何删除C程序中的重复输出?
How to remove duplicate output in C program?
我创建了一个从用户输入中获取字符的程序。它将字母转换为大写并将其显示给最终用户。
但是,我收到一个输出问题,我得到双倍的 "Please enter a character in lower case:" 和下面的额外一行。我不太确定是什么原因造成的,但这是我目前的程序:
#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
我创建了一个从用户输入中获取字符的程序。它将字母转换为大写并将其显示给最终用户。
但是,我收到一个输出问题,我得到双倍的 "Please enter a character in lower case:" 和下面的额外一行。我不太确定是什么原因造成的,但这是我目前的程序:
#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