涉及字符的表达式或其他类似的问题 [英] Big trouble with character-involved expressions or something like that

查看:76
本文介绍了涉及字符的表达式或其他类似的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我对涉及人物的操纵感到困惑,我甚至不知道如何提出正确的问题。我在这里举个例子:



我想让我的程序通过输入y或n来询问用户是否要从某个循环中断br />
以下是我的代码的一些简化版本无效:



1.)

Right now I'm so confused by manipulation involving "characters" that I don't even know how to ask a proper question. I'll just give an example here:

I want to let my program ask the user whether to break from some loop by entering "y" or "n"
Here are some simplified versions of my code that did not work:

1.)

char option;

//SOME LOOP
{
    //SOME STUFF
    printf("Do you want to continue (y or n)? ");
    scanf_s("%c" , &option);
    if (option == 'n')
         break;
}





2.)





2.)

int option;

//SOME LOOP
{
    //SOME STUFF
    printf("Do you want to continue (y or n)? ");
    scanf_s("%d" , &option);
    if (option == (int)'n')
         break;
}





我知道我一定错过了重要的东西,但我不知道它是什么。非常感谢任何帮助!



I know I must have missed something important but I don't know what it is. Any help is appreciated very much!

推荐答案

可能它确实有效 - 它只是没有按照你期望的那样做。请记住,scanf_s在完成输入行时实际上只做任何事情:所以要退出循环,用户需要输入n并按ENTER键。



但是您的代码还有另一个问题:如果您查看文档: http://msdn.microsoft。 com / en-us / library / w40768et.aspx [ ^ ]它确实说得很清楚:

Probably, it does work - it just doesn't do what you expect, when you expect it to. Remember that scanf_s only actually does anything when you finish the input line: so to exit the loop, your user needs to enter "n" and press the ENTER key.

But there is another problem with your code: If you look at the documentation: http://msdn.microsoft.com/en-us/library/w40768et.aspx[^] it does say quite clearly what is wrong:
In the case of characters, a single character may be read as follows:
char c;
scanf_s("%c", &c, 1);





告诉它你想要多少个字符读! :笑:



So tell it how many characters you want to read! :laugh:

main( )
	{
    char option;
 
    //SOME LOOP
    while(1==1)
        {
        //SOME STUFF
        printf("\nDo you want to continue (y or n)? ");
        scanf_s("%c" , &option, 1);
        if (option == 'n')
             break;
        }
	}


这篇关于涉及字符的表达式或其他类似的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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