[英]A short program that takes input lower case letters it gives the upper case letters and exits at when the enter key is pressed
The conversion works correctly but when I press enter, when asked for a lower case, it executes an enter (\\n) and doesn't exit or stop. 转换正常进行,但是当我按Enter键时,当要求输入小写字母时,它将执行输入(\\ n)且不会退出或停止。
This is my program: 这是我的程序:
#include <stdio.h>
#include <math.h>
main()
{
char ch;
printf("Press a letter: ");
while (scanf(" %c",&ch)!='\n')
{
printf("%c\n",ch-32);
}
}
Your program is incorrect: 您的程序不正确:
scanf
does not return the character that has been read, it returns the number of scanned items scanf
不返回已读取的字符,则返回扫描的项目数 '\\n'
is to check if (ch == '\\n') break;
'\\n'
一种方法是检查if (ch == '\\n') break;
toupper
function instead of using subtraction directly. toupper
函数,而不是直接使用减法。 use this code : 使用此代码:
#include <stdio.h>
#include <math.h>
main()
{
char ch;
printf("Press a letter: ");
while (1)
{
scanf(" %c",&ch);
if(ch=='\n')
break;
printf("%c\n",ch-32);
}
}
scanf(" %c",&ch)
will never set ch
to \\n
as the space in the format consumes all white-space, including '\\n'
before moving on to "%c"
. scanf(" %c",&ch)
永远不会将ch
设置为\\n
因为格式中的空格会占用所有空白,包括'\\n'
然后再移至"%c"
。
Further, the return value from scanf()
is EOF or the number of successfully parsed arguments, not ch
. 此外,
scanf()
的返回值为EOF或成功解析的参数的数量,而不是ch
。 (not "%n"
though) (虽然不是
"%n"
)
Consider: 考虑:
#include <stdio.h>
// No need for #include <math.h>
#include <ctype.h>
int main() {
int ch; // use int
printf("Press a letter: ");
while ((ch = fgetc(stdin)) != EOF && (ch != '\n')) {
printf("%c\n", toupper(ch));
}
return 0;
}
OP states in another comment "we should perform this without using outside functions, for example, my professor didn't teach us toupper". OP在另一条评论中指出:“我们应该在不使用外部功能的情况下执行此操作,例如,我的教授没有教我们如何学习”。 Let's assume
stdio
functions are OK and ctype
ones are not. 假设
stdio
函数正常,而ctype
函数无效。
// Assume ASCII encoding
while ((ch = fgetc(stdin)) != EOF && (ch != '\n')) {
if ((ch >= 'a') && (ch <= 'z')) {
ch += 'A' - 'a';
}
printf("%c\n", ch);
}
// Not assuming ASCII encoding, but letters a-z, A-Z
while ((ch = fgetc(stdin)) != EOF && (ch != '\n')) {
static const char *az = "abcdefghijklmnopqrstuvwxyz";
static const char *AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i;
for (i=0; az[i]; i++) {
if (ch == az[i]) {
ch = AZ[i];
break;
}
}
printf("%c\n", ch);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.