[英]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;
}
您的程序中有很多問題-
char *filename;
在int load_data(char* filename, int *x, float *y)
您傳遞的是filename
但是filename
中沒有存儲name of file
。 fscanf(file, "%d%f", &x, &y);
當您使用%d
在fscanf
傳遞指針時,您不需要&
運算符。
fscanf(file, "%d%f", x, y);
您需要使用malloc為x
和y
分配內存。
這兩個函數的size
不同,因為您在函數和main
再次聲明了它。這就是為什么int main
size
始終為0
原因。
void print_data
在此函數中,您正在打印acn
和amt
值,但是兩個指針都未初始化,並且正在打印它,因此它將給出未定義的行為。
另外,您還有在程序中聲明但未使用的指針。
在下面的代碼行(已發布)中, 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.