一旦在C中获得输入,就忽略该行的其余部分 [英] Ignoring the rest of the line once input has been gotten in C

查看:66
本文介绍了一旦在C中获得输入,就忽略该行的其余部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出如下输入:

6 2
1 2 3 4 5 6
4 3 3 4 5 6 

第一个数字在哪里 第一行是行中的变量数,第二行是行数.

Where first number in first line is number of variables in line, second one is number of lines. How it is possible to get only first n/2 values, where n is number of values in a line and skip to the next line?

推荐答案

我很惊讶没有人提到fscanf("%*d")-*符号告诉fscanf读取整数值,但忽略它(请参阅文档此处).这使您可以执行以下操作:

I'm surprised no one mentioned fscanf("%*d") - that * sign tells fscanf to read an integer value, but to ignore it (see the documentation here). This lets you do something like:

int numbers[MAX_NUMS];
int n = numbers_in_line();
for( i = 0; i < n; i++ )
   if(i<n/2)
      fscanf("%d", &numbers[i]);
   else
      fscanf("%*d");

这似乎比仅阅读其余字符更清楚.如果您提前知道n,也可以这样写:

which seems clearer than just reading in the rest of the chars. If you knew n ahead of time, you could also just write:

scanf("%d %d %d %*d %*d %*d",&numbers[0],&numbers[1],&numbers[2]);

您没有直接询问这个问题,但是如果您正在读取二进制数据,则还有另一种跳过该行其余部分的方法.您可以读取所需的数据,然后计算下一行开头的位置(此处使用一些指针算法),然后使用

You didn't ask about this directly, but if you were reading binary data, there is an additional way to skip the rest of the line. You could read what data you want, then calculate the location of the beginning of the next line (some pointer arithmetic here) and use the fseek function to jump ahead to that location, which could save some I/O time. Unfortunately, you can't do this with ASCII data because the numbers do not take up uniform amounts of space.

这篇关于一旦在C中获得输入,就忽略该行的其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆