English 中文(简体)
C. 选择和印刷果园?
原标题:Getting and printing chars in C?
  • 时间:2009-09-10 16:15:52
  •  标签:

How do I get and print a char from a user? This want do it...

#include <stdio.h> 
int main() {

    float number1;
    char mychar =    ;

    printf("Number?
");
    scanf("%f", &number1);

    printf("Character?
");
    scanf("%c", &mychar);

    printf("You typed number: %f
", number1);
    printf("You typed the char: %c
", mychar);
}
最佳回答

你再次看到的问题是,它确实是看一看一面的,但它只是你所期望的特性。 扫描的确是格式化的投入。 你第一次说了,你再次告诉我们,我们会期望一些。 但是,你们真正进入了不止几个方面:

Number?
1234.5678<enter>

When you press the enter key, it is actually inserting a character into your input stream. As you may know, we use to represent newline, the character you get when you press enter. So your input stream actually looks like "1234.5678 ".

So scanf does its thing and reads 1234.5678 and then it sees . It says "oh, that s not part of the number, so I ll stop." Well, your input still has the . The next time you call scanf, you tell it to read a character. The user types whatever they want, but that goes behind the from the previous scanf. So scanf tries to match the input stream with a character and says "ok, the first thing in this input stream is a character, and it s , so I ll return that." The stuff the user typed is still sitting in the input stream.

So a simple way to get rid of it is to have a loop that empties all remaining characters from the input stream until it finds .

printf("Number?
");
scanf("%f", &number1);
while( getchar() !=  
 );

在这次空闲活动之后,你的投入流将是空洞的。 因此,在你称之为扫描时,它会等到用户打造某种东西,并将使用用户分类的任何东西。

还指出,扫描仪有收益价值,在打电话后应加以核对。 阅读扫描,看看它返回的情况。

问题回答

各位评论说,你提出的问题已经包括答案。 但无论如何:

如果你想在++中做同样的事情,你可以使用:

int mynumber;
char mychar;
cout << "Number?" << endl;
cin >> mynumber;
cout << "Character?" << endl;
cin >> mychar;
cout << "you typed number " << mynumber << " and char " << mychar << endl;

当然,你 将在C++实施。

(如果你正在开发更严格的申请,我将建议使用比单纯的焚化或扫描更先进的方法。)

在C,你不需要使用扫描仪来获得单一特性。 您可以使用“Sapchar()”的功能:

printf("Would you like a donut? [Y/N] ");
answer = getchar();

switch(answer) {
    case  y :
    case  Y :
        printf("Mmmm... donuts!");
        break;
    case  n :
    case  N :
        printf("Eugh... donuts?");
        break;
    default:
        printf("You should never ignore code offering donuts.");
        break;
}  

look、 get等





相关问题
热门标签