我正在编写一个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个整数的数组之前,如何跳过某些行?
3 回答
你得到一个段错误,因为你第一次调用scanf需要3个参数 .
您可以使用
*
指定可选参数,例如scanf("%*s");
将读取一个字符串并将其丢弃 .从
scanf
手册页:要使用
scanf
,您需要一个地址指针来进行扫描 . 我认为你可以使用没有地址的格式化程序来放置结果 . 我只是将它们放在nums
,nums + 1
和nums + 2
中,因为无论如何它们都会被你想要的行覆盖 .我建议你不要做任何事情,因为你知道在哪里存储行输入
(nums, nums+1, nums+2)