我正在编写一个 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 byscanf()
.
关于c - 如何使用 scanf 跳过标准输入的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23049905/