【问题标题】:How to use scanf or use a different input reading method?如何使用 scanf 或使用不同的输入读取方法?
【发布时间】:2021-11-22 21:53:55
【问题描述】:

这里是 C 的新手,有点挣扎。

我正在读取如下所示的输入:

9, 344, 100
10, 0, 469
...

我正在尝试对每一行进行分组,以便我可以将每 3 个数字作为参数发送到函数中。

我一直在尝试使用scanf,但因为它映射到内存地址,所以我在保留每行之后的数字时遇到了问题。我不知道我将拥有多少行数据,所以我无法制作一定数量的数组。另外,我仅限于<stdio.h>中的功能。

如果我使用scanf,我是否可以避免使用 malloc?

我在下面附上了一个想法。寻找建议,也许可以澄清scanf 的工作原理。

抱歉,如果我在这里遗漏了一些明显的东西。

int main() {
  int i = 0;
  int arr[9]; //9 is just a test number to see if I can get 3 lines of input
  char c;
  while ((c = getchar()) != EOF) {
    scanf("%d", &arr[i]);
    scanf("%d", &arr[i + 1]);
    scanf("%d", &arr[i + 2]);
    printf("%d, %d, %d\n", arr[i],
      arr[i + 1], arr[i + 2]); //serves only to check the input at this point
      //at this point I want to send arr 1 to 3 to a function
    i += 3;
  }
}

这段代码的输出是一堆内存地址和一些正确的值。 像这样的:

0, 73896, 0
0, 100, -473670944

什么时候应该读:

0, 200, 0
0, 100, 54
int main(){
    char c;
    while ((c=getchar()) != EOF){
        if (c != '\n'){
            int a;
            scanf("%d", &a);
            printf("%d ", a);
        }
        printf("\n");
    }
}

此代码正确打印出输入,但不允许我在 while 块中多次使用 scanf 而不会出现内存问题。

【问题讨论】:

  • 你不知道你得到了什么,因为你没有检查 scanf 的返回值。
  • 函数:getchar() 返回 int,而不是 char。代码(取决于编译器上的charsignness)将无法识别EOF。强烈建议将:char c;替换为int c;

标签: c scanf


【解决方案1】:

一个选项是同时扫描所有三个。您还需要匹配输入中的逗号 (,)。

例子:

#include <stdio.h>

int main() {
    int arr[9];

    int i = 0;
    for(; i + 3 <= sizeof arr / sizeof *arr // check that there is room in "arr"
          &&                               // and only then, scan:
          scanf(" %d, %d, %d", &arr[i], &arr[i+1], &arr[i+2]) == 3;
          i += 3)
    {
        printf("%d, %d, %d\n", arr[i], arr[i+1], arr[i+2] );
    }
}

【讨论】:

    【解决方案2】:

    我宁愿使用fgetssscanf

    
    char buff[64];
    
    /* .......... */
    
    if(fgets(buff, 63, stdin) != NULL)
    {
        if(sscanf(buff, "%d,%d,%d", &arr[i], &arr[i + 1], &arr[i + 2]) != 3)
        {
            /* handle scanf error */
        }
    }
    else
    {
        /* handle I/O error / EOF */
    }
    

    【讨论】:

    • OP 也在询问避免 malloc。行数事先不知道
    • OP 想要解决 X-Y 问题。 malloc 或固定大小的数组。没有别的办法
    • UV 为正确的fgets() / sscanf()。仅使用scanf(),您就是一个格式错误的字符或额外字符,不会从那时起破坏所有输入......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    相关资源
    最近更新 更多