丢弃标题行

问题描述 投票:0回答:1

我有一个.tsv文件,我在编译读取文件的代码后直接输入到我的代码中或使用“<”表示的任何内容。我只是在整个代码中使用scanf来读取数据行,而不是任何fopen。标题是3个非双字符,意味着要读取然后丢弃,以便我可以将3列中的每个双精度放入单独的数组中。

我似乎无法让我的代码跳过.tsv文件的第一行输入,然后实际抓住3个双打并将它们放入3个独立的数组中。

int main(int argc, char *argv[])
{

    int i = 0;
    double X[MAX], Y[MAX], KG[MAX];
    void data_lines();
    while (scanf("%lf%lf%lf",&X[i],&Y[i],&KG[i] )== 3) {
        printf("%lf%lf%lf\n", X[i],Y[i],KG[i]);
        i++;
    }
    printf("%d", MAX);
    return 0;
}

void 
data_lines() {
    char ch;
    while (scanf("%c",&ch)!=EOF) {
        if (ch == '\n'){
            return;
        }
    }
}

当我输出这个代码时,我得到的只是999打印。所以我猜我的数组没有任何东西,第一条数据线没有被跳过。

c
1个回答
0
投票

以下提议的代码:

  1. 干净利落地编译
  2. 执行所需的功能

注意前向参考/原型

请注意调用子函数的方式

请注意头文件的方式:包括stdio.h

注意MAX值的定义

现在,建议的代码:

// the header file needed for the function: scanf() and function: printf() and the value: EOF
#include <stdio.h>

// define a value and give it a meaningful name
#define MAX 50

// prototypes  notice the prototype has 'void' but the actual function has nothing between the parens
void data_lines( void );

// notice the signature when the parameters are not used
int main( void )
{
    int i = 0;
    double X[MAX], Y[MAX], KG[MAX];

    // call the sub function
    // which returns nothing and has no parameters
    data_lines();

    while (scanf("%lf%lf%lf",&X[i],&Y[i],&KG[i] )== 3) 
    {
        printf("%lf%lf%lf\n", X[i],Y[i],KG[i]);
        i++;
    }
    printf("%d", MAX);
    return 0;
}


void data_lines() 
{
    char ch;
    while (scanf("%c",&ch)!=EOF) 
    {
        if (ch == '\n')
        {
            return;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.