带有可选输入的C scanf

问题描述 投票:0回答:1
char value1[10]; int value2; int value3 = 0;
if (!scanf("%s %d %d", &value1[0], &value2, &value3)) { scanf("%s %d", &value1[0], &value2); } ;

我正在尝试使用scanf插入3个值,但是如果收到2个,它将取2个值。找不到使用scanf的任何答案。一直尝试使用fgets,但标准输入中的值仍然保留。

c scanf
1个回答
0
投票
char value1[10]; int value2; int value3 = 0;
if (!scanf("%s %d %d", &value1[0], &value2, &value3)) { scanf("%s %d", &value1[0], &value2); } ;

一件小事:不要使用&value1[0],请使用value1。数组将衰减为指向其第一个元素的指针,并且在概念上,要将字符串存储在value1中。

第二,您只需调用一次scanf,然后查看其返回值。这将告诉您读入了多少个值。在这种情况下,您并不在乎,因此可以使用:

if (scanf("%s %d %d", value1, &value2, &value3) < 2)
    { /* error handling */ }
else // we read in 2 or 3 entries, life is good
    { /* success handling */ }
© www.soinside.com 2019 - 2024. All rights reserved.