我不明白为什么我不能让在C三个输入 [英] I don't understand why I can't get three inputs in c

查看:141
本文介绍了我不明白为什么我不能让在C三个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个朋友是想学C(她自己,一本书),有时她向你寻求帮助。

A friend of mine is trying to learn c (on her own, with a book) and sometimes she asks for help.

她刚才给我的东西我不能回答;我很惭愧,但我研究下在大学,然后转移到PHP。我真的很坚持,所以我想知道为什么我们不能得到三个输入。这里的局部code:

She just showed me something I can't answer; I'm ashamed but I studied C in college and then moved to php. I'm really stuck so I would like to know why we can't get three inputs. Here's partial code:

#include <stdio.h>

int main()
{
    int num1;
    int num2;
    char x;

    printf("Enter a number:\n");
    scanf("%d\n",&num1);
    printf("Enter another number:\n");
    scanf("%d\n",&num2);
    printf("Choose an operation sign:\n");
    scanf("%c\n",&x);

...

喜欢这个要求第一个输入两次,像这样的:

Like this it asks for the first input two times, like this:

Enter a number:
1
2
Enter another number:
3
Choose an operation sign:
-

如果我删除 \\ n 它跳过最后一个 scanf函数

If I remove the \n it skips the last scanf.

你能帮我明白为什么?

推荐答案

在这里阅读:<一href=\"http://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer/5240807#5240807\">scanf()叶新行字符缓冲区?

解决方案:

int main()
{
    int num1;
    int num2;
    char x;

    printf("Enter a number:\n");
    scanf("%d",&num1);
    printf("Enter another number:\n");
    scanf("%d",&num2);
    printf("Choose an operation sign:\n");
    scanf("\n%c",&x); /* See the \n <---------------- */
}

这是另一种:

char buf[2]; /* We need 2 characters for the null */
scanf("%1s", buf); /* We ask max 1 character (plus null given by scanf) */
char x = buf[0]; /* We take the first character */

作为一个小纸条,感谢如何 scanf函数的作品,同时与解决方案,您可以直接在第一个输入的所有数据和各种<$ C插入$ C> scanf函数将自己的一部分。所以,你可以插入 123 234 + ,它会在三个变量进行分割正确。

As a small note, thanks to how scanf works, with both the solutions you can insert directly in the first "input" all the data and the various scanf will take their part. So you could insert 123 234 + and it would be split in the three variables correctly.

这篇关于我不明白为什么我不能让在C三个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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