简体   繁体   English

如何在C中检查scanf两个整数

[英]How to check scanf two integers in c

I have a problem, that I need to scan two integers in one line divided by a space, so the code looks something like this: 我有一个问题,我需要在一行中扫描两个整数并除以一个空格,因此代码看起来像这样:

scanf("%d %d",&integer1,&integer2);

And in this code I need to check whether there were scanned two integers. 在这段代码中,我需要检查是否扫描了两个整数。 Can someone help me? 有人能帮我吗? Thank you in advance 先感谢您

By default scanf() reads the space there is no meaning in giving space. 默认情况下, scanf()读取空格,而给出空格没有任何意义。 If you want to read two integers scanf("%d %d",&integer1,&integer2); 如果要读取两个整数scanf("%d %d",&integer1,&integer2); and scanf("%d%d",&integer1,&integer2); scanf("%d%d",&integer1,&integer2); both will help you. 两者都会帮助你。

It will accept the following inputs: 它将接受以下输入:

1 2
12 22
3 2 5 //EOF

your program will pass only after reading two integers. 您的程序仅在读取两个整数后才能通过。 You don't need to check anything. 您无需检查任何内容。

To eliminate EOF 消除EOF

By default scanf returns number of values read so make use of it. 默认情况下, scanf返回读取的值的数量,因此请充分利用它。

if(scanf("%d%d",&integer1,&integer2) != 2)
{
   //if more than two values are entered
   //perform some error handling
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM