本文介绍了奇怪的循环不会使用%C工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我靠在C编程。我写了一个奇怪的循环,但同时我用%C scanf()函数无法正常工作。结果这里是code:

I am leaning C programming. I have written an odd loop but doesn't work while I use %c in scanf().
Here is the code:

#include<stdio.h>
void main()
{
    char another='y';
    int num;
    while ( another =='y')
    {
        printf("Enter a number:\t");
        scanf("%d", &num);
        printf("Sqare of %d is : %d", num, num * num);
        printf("\nWant to enter another number? y/n");
        scanf("%c", &another);
    }
}

但是,如果我用%S 在这个code,例如 scanf函数(%S,&安培;另一人); ,然后它工作正常。结果为什么会出现这种情况?任何想法?

But if I use %s in this code, for example scanf("%s", &another);, then it works fine.
Why does this happen? Any idea?

推荐答案

%C 转换读取输入的下一个字符,不管它是什么。在这种情况下,你已经previously读取使用一些%d个。你必须按下回车键读取这个数字,的的你还没有做任何事情来读取从输入流的新线。因此,当你做了%C 的转换,它读取新线从输入流(而无需等待你真正输入任何内容,因为有已投入等着被读)。

The %c conversion reads the next single character from input, regardless of what it is. In this case, you've previously read a number using %d. You had to hit the enter key for that number to be read, but you haven't done anything to read the new-line from the input stream. Therefore, when you do the %c conversion, it reads that new-line from the input stream (without waiting for you to actually enter anything, since there's already input waiting to be read).

当您使用%S ,它会跳过在任何领先的空白,以获得比空白一些其他字符。它把新线为空白,因此跨等待新线它含蓄地跳过。由于有(presumably)闲来无事等待读,进入等待你输入的东西,你显然希望。

When you use %s, it skips across any leading white-space to get some character other than white-space. It treats a new-line as white-space, so it implicitly skips across that waiting new-line. Since there's (presumably) nothing else waiting to be read, it proceeds to wait for you to enter something, as you apparently desire.

如果你想使用%C 的转换,你可以precede它与格式字符串中的空间,这也将在任何涂白跳过流中的空间。

If you want to use %c for the conversion, you could precede it with a space in the format string, which will also skip across any white-space in the stream.

这篇关于奇怪的循环不会使用%C工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:06