C使用文字变数 [英] C Do While with character variables

查看:87
本文介绍了C使用文字变数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码不起作用

why this Code is Not Working

 void main()
 {
char op;
do
{
      printf("Hello ");

  printf("\nPress Y for continue and N for Exit");
  scanf("%c",&op);
}while(op == 'Y' || op == 'y');
 }



请帮助我,如果我将op用作整数并应用条件"while(op> 0)"
,类似的代码将起作用



plz help me out similar code will working if i take op as integer and apply condition "while(op > 0)"

[edit]Code block added - OriginalGriff[/edit]

推荐答案

它对我来说很好-或至少可以完全满足我的期望:
打印你好"
打印按Y继续,按N退出"
等待我键入并按[ENTER]
查看我输入的第一个字符:如果它是小写字母"Y"的大写,它将重复,否则退出.

在按[ENTER]之前,您是否尝试过键入"YYYYyyyyy"?
因为如果您这样做,它会循环9次...

基本上,您的代码正在寻找循环的原因-"Y"的存在.如果得到任何其他字符,则退出. [ENTER]键在字符串中添加一个"\ n"字符,因此当您的代码遇到该字符时,它将退出循环.您最好仔细检查一下输入内容! :laugh:
It works fine for me - or at least it does exactly what I expect it to do:
Print "Hello"
Print "Press Y for continue and N for Exit"
Wait for me to type and press [ENTER]
Looks at the first character I type: If it is a upper of lower case ''Y'' it repeats, otherwise it exits.

Have you tried typing "YYYYyyyyy" before you press [ENTER]?
Because you will find it loops 9 times if you do...

Basically, your code is looking for a reason to loop - the presence of a ''Y''. If it gets any other character, it exits. The [ENTER] key adds a ''\n'' character to the string, so when your code meets it, it exits the loop. You would be better off checking your inputs a bit more carefully! :laugh:


尝试一下



Try this



char op;
    do
    {
       printf("Hello ");

      printf("\nPress Y for continue and N for Exit\t");

      scanf("%c",&op);

    }while(op == 'y' || op == 'Y' ||op =='\n');


这篇关于C使用文字变数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆