c - 如何使用 scanf 跳过标准输入的一部分?

标签 c

我正在编写一个 c 程序,我的标准输入看起来像这样。

2
1 3 4
6 9 1
3 6 0
3 5 1
2 6 1

我的 C 程序将第一个数字存储在名为 rowToConsider 的变量中。然后,我将第 rowToConsider 行(从 0 开始索引)的数字读取到数组 nums 中。

#include<stdio.h>

int main() {
  int rowToConsider;
  int nums[3];

  scanf("%d", &rowToConsider);

  for (int i = 0; i < rowToConsider; i++) {
    // My attempt to read a row into nothing. Basically, just skip the row.
    scanf("%d %d %d");
  }

  scanf("%d %d %d", nums, nums + 1, nums + 2);  
}

但是,for 循环中的 scanf 触发了段错误。

如何在读取 3 个整数的数组之前跳过一些行?

最佳答案

您遇到了段错误,因为您对 scanf 的第一次调用需要另外 3 个参数。

您可以使用 * 指定可选参数,例如scanf("%*s"); 将读取一个字符串并将其丢弃。

来自 scanf 手册页:

An optional '*' assignment-suppression character: scanf() reads input as directed by the conversion specification, but discards the input. No corresponding pointer argument is required, and this specification is not included in the count of successful assignments returned by scanf().

关于c - 如何使用 scanf 跳过标准输入的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049905/

相关文章:

c - Unix 代码中的这个 C 可能有什么问题

c - 将寄存器的内容读入 C 变量时的奇怪行为

c - 测试1.c :7: error: syntax error before '{' token

在matlab中调用C函数的变量地址

c - 返回正确值但目标变量错误的 C 函数调用

c - 为什么要根据 C 中的其他宏递归定义宏?

c++ - tinycthread编译错误

c - 使用移位和或操作进行缓冲操作

c - Linux sizeof struct @运行时?

c - 之前存储的字符串会被 fget 覆盖