簡體   English   中英

命令行參數問題

[英]command line arguments issues

目前程序正在讀取“無法打開輸入文件”,這意味着大小為0。我用編輯器制作了輸入文件,但不確定是什么問題。 我的代碼有什么問題可能導致這種情況? 還是更有可能只是搞砸了input.txt文件?

#include <stdio.h>
#include <stdlib.h>

int load_data(char* filename, int *x, float *y)
{
    int i=0;

    FILE* file=fopen(filename,"r");


    if(file==NULL)
    {
            return 0;
    }

    int size;


    fscanf(file, "%d", &size);

    for(i=0;i<size;i++)
    {
            fscanf(file, "%d%f", &x, &y);
    }


    fclose(file);
    return size;
}


void print_data(int *acn, float *amt, int size)
{
    int i;
    int *p;

    for(i=0;i<size;i++)
    {
            printf("%-10d%-10f ", *(acn+i), *(amt+i));
    }
}

int main(int argc, char** argv)
{
    int size=0, *x;
    char *filename;
    float *y;

    if(argc!=3)
    {
            printf("\nInsufficient arguments.\n");
            return 0;
    }


    int n=atoi(argv[2]);

    int *acn;
    float *amt;


    int *fp=malloc(sizeof(int)*n);


    if(size==0)
    {
            printf("\nUnable to open the input file.\n");
            return 0;
    }
    load_data(filename, x, y);
    print_data(acn, amt, size);

    free(fp);
    return 0;
}

您的程序中有很多問題-

  1. 您是逗號行中的文件名,但沒有將其存儲在char *filename; int load_data(char* filename, int *x, float *y)您傳遞的是filename但是filename中沒有存儲name of file
  2. fscanf(file, "%d%f", &x, &y); 當您使用%dfscanf傳遞指針時,您不需要&運算符。

     fscanf(file, "%d%f", x, y); 
  3. 您需要使用malloc為xy分配內存。

  4. 這兩個函數的size不同,因為您在函數和main再次聲明了它。這就是為什么int main size始終為0原因。

  5. void print_data在此函數中,您正在打印acnamt值,但是兩個指針都未初始化,並且正在打印它,因此它將給出未定義的行為。

  6. 另外,您還有在程序中聲明但未使用的指針。

在下面的代碼行(已發布)中, size變量的值為0 在檢查if(size==0)行之前,從未更新過該值。 這就是為什么if check返回true並顯示"Unable to open the input file"

if檢查,您可能需要在此之前設置size變量的值。

int size=0, *x;    //HERE YOU ARE WRITING "SIZE" VARIABLE
char *filename;
float *y;

if(argc!=3)
{
        printf("\nInsufficient arguments.\n");
        return 0;
}

int n=atoi(argv[2]);
int *acn;
float *amt;

int *fp=malloc(sizeof(int)*n);
if(size==0) //HERE YOU ARE READING/CHECKING "SIZE" VARIABLE. THERE IS NO CHECGE IN VARIABLE BEFORE THIS SO, VALUE IS STILL '0'
{
        printf("\nUnable to open the input file.\n");
        return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM