作者markoo (上行下笑阿..)
看板NCTU-STAT98G
標題0730 程式 從命令提示字元外部輸入參數
時間Sat Aug 1 23:16:49 2009
同學, 這程式幾個重點 可以細細品味
1. 讀文字檔用fscanf
(可以一次讀一個, 也可以一次讀一排 當然也可以一次讀完 只是要寫很長)
2. 由命令提示字元外部輸入參數
3. atoi 與 strcpy 兩個函式的用法
4. 結構的指標變數宣告方式
5. 由命令提示字元執行.exe時 記得要把.txt檔案放在對應的資料夾下
或者直接"C:\Documents and Settings\Joanne\桌面\0730\Debug\mydata.txt"
給路徑指到指定的.txt檔
程式如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *in;
struct data {
int X;
float Y;
double Z;
} *mydata;
/*根據資料型態決定結構內該有的分量
ex:mydata.txt的資料型態為 int, float, double.*/
int main(int argc, char **argv)
{
if (argc!=3)
{
printf("Input error. Try: class12.exe mydata.txt 10\n");
exit(0);
}
/* 這邊只是設定希望輸入者輸入正確的參數,輸入錯誤則結束程式: exit(0);
其實從命令提示字元輸入"過多參數" 對程式並無影響 (why?)
只是要求輸入格式可以減少輸入者犯的錯誤 */
printf("argv[0] = %s\n",argv[0]);
printf("argv[1] = %s\n",argv[1]);
printf("argv[2] = %s\n",argv[2]);
/* 這邊把外部輸入的參數一一列出,
此時輸入的參數都設定為char, 所以要用%s才能印出 */
int i;
int n;//sample size
char name[250];//file name of .txt
n = atoi(argv[2]);//把數字字串轉換成整數型態appoint to integer
mydata = (struct data *) malloc (n*sizeof(struct data));
strcpy(name,argv[1]);
/*根據不同的程式與不同的需求決定自己的程式哪些參數可以由外部輸入
這邊我們設定把兩個參數由 "命令提示字元"做外部輸入
這兩個參數分別為:n (sample size)和 name (讀入檔案名稱)*/
in = fopen(name,"rt");
i=0;
while (!feof(in))
/* while(!feof(in))的意思是,直到讀到(in開啟的)檔案結尾(end of file)前,
執行下面步驟*/
{
fscanf(in,"%d%f%lf\n",&mydata[i].X,&mydata[i].Y,&mydata[i].Z);
/*這邊注意fscanf不讀斷行空白還有Tab
所以這邊要讀檔案內的數字 只需要把該讀近的數字類型依次宣告為
%d(int)%f(float)%lf(double)即可*/
printf("%d\t%f\t%lf\n",mydata[i].X,mydata[i].Y,mydata[i].Z);
i++;
}
fclose(in);
return 0;
}
mydata.txt內容如下:
12 15.6 0.76543
100 25.9 0.89702
50 17.9 0.12540
33 10.7 0.256
34 9.8 0.099
89 15.8 0.568
156 45.5 0.78954
33 12.5 0.1247
24 10.5 0.0998
58 23.2 0.78902
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.166.48.157