繁体   English   中英

一个简短的程序,接受输入的小写字母,它给出大写字母,并在按Enter键时退出

[英]A short program that takes input lower case letters it gives the upper case letters and exits at when the enter key is pressed

转换正常进行,但是当我按Enter键时,当要求输入小写字母时,它将执行输入(\\ n)且不会退出或停止。

这是我的程序:

#include <stdio.h>
#include <math.h>



main()
{
 char ch;
 printf("Press a letter: ");
 while (scanf(" %c",&ch)!='\n')
    {
        printf("%c\n",ch-32);     
    }


}

您的程序不正确:

  • scanf 返回已读取的字符,则返回扫描的项目数
  • 处理'\\n'一种方法是检查if (ch == '\\n') break;
  • 您需要在减去32之前检查字符是否确实是字母
  • 您应该使用toupper函数,而不是直接使用减法。

使用此代码:

#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)永远不会将ch设置为\\n因为格式中的空格会占用所有空白,包括'\\n'然后再移至"%c"

此外, scanf()的返回值为EOF或成功解析的参数的数量,而不是ch (虽然不是"%n"

考虑:

#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在另一条评论中指出:“我们应该在不使用外部功能的情况下执行此操作,例如,我的教授没有教我们如何学习”。 假设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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM