如何在一个读取3个变量的scanf中输入2个变量

huangapple go评论89阅读模式
英文:

How to Input 2 Variables in a scanf that reads 3

问题

所以,我想要一个输入,它可以接受3个不同变量(int和char)。但我希望有一个选项,即使只提供2个变量,也能打印出一些内容。如何使用scanf实现这一点,如果可能的话,使用基本的C语言,而不使用Ctrl+D,也不要太高级,谢谢。

#include <stdio.h>

int main(void) {
  char y;
  int i;
  int x;
  int a;
  printf("输入:");
  a = scanf("%c %d %d", &y, &i, &x);
  if (a >= 2) {
    printf("%c %d", y, i);
  }
}
英文:

So, I want to have an input where it can take 3 inputs of different variables (int and char). But I want to have an option where an output prints out something even if only 2 variables are given. How do I make this possible using scanf and if possible something that has basic C whilst not using Ctrl+D and not too advanced, Thanks.

#include &lt;stdio.h&gt;

int main(void) {
  char y;
  int i;
  int x;
  int a;
  printf(&quot;Enter Input: &quot;);
  a = scanf(&quot;%c %d %d&quot;, &amp;y, &amp;i, &amp;x);
  if(a == 2) {
    printf(&quot;%c %d&quot;, y, i);
  }
}

答案1

得分: 3

避免常见的 scanf 陷阱的一般建议是改为使用 fgets 读取完整的输入行,然后在内存中使用 sscanf 解析这些行(或使用遵循相同模式的工具,例如 getline(POSIX)+ strspn / strcspn / strtol 等)。

scanf 在未满足转换条件并且 stdin 未达到 EOF(或出错)时等待更多输入的方式不同,sscanf 不会等待未满足的转换条件,因为不会突然有更多字符串需要解析。

示例用法:

 % ./a.out
Enter Input: a 2
a | 2
 % ./a.out
Enter Input: a 2 4
a | 2 | 4
英文:

The general advice for avoiding common pitfalls with scanf is to instead read entire lines of input with fgets, and then parse those lines in-memory with sscanf (or use tools that follow the same pattern, e.g., getline (POSIX) + strspn / strcspn / strtol, etc.).

Unlike how scanf waits for more input when it has an unfulfilled conversion and stdin has not reached EOF (or error), sscanf does not wait on an unfulfilled conversion because it is not like there will suddenly be more string to parse.

#include &lt;stdio.h&gt;

int main(void) {
    char buffer[256];
    printf(&quot;Enter Input: &quot;);

    if (!fgets(buffer, sizeof buffer, stdin))
        return 1;

    char y;
    int i;
    int x;

    int rc = sscanf(buffer, &quot;%c%d%d&quot;, &amp;y, &amp;i, &amp;x);

    if (rc &lt; 2)
        return 1;

    if (rc &lt; 3)
        printf(&quot;%c | %d\n&quot;, y, i);
    else
        printf(&quot;%c | %d | %d\n&quot;, y, i, x);
}

Example usage:

 % ./a.out
Enter Input: a 2
a | 2
 % ./a.out
Enter Input: a 2 4
a | 2 | 4

huangapple
  • 本文由 发表于 2023年7月27日 19:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76779338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定