我遇到了這個程序的問題,當我使用stdin的時候它工作的很好,但是當我修改它以從命令行獲取字符時,它不會。我知道我做錯了什麼,但不知道什麼,任何幫助將不勝感激。C,使用argv []作爲命令行參數
說明和代碼:
/* Program prints the date in this form: September 13, 2010
allow the user to enter date in either 9-13-2010 or 9/13/2010
format, otherwise print 'error' */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *month(int m)
{
char *months[]={"January","February","March","April","May",
"June", "July","August","September","October",
"November","December"};
return months[m-1];
}
int main(int argc, char *argv[])
{
int m=0,d=0,y=0;
FILE *fp;
if((fp=fopen(argv[1],"rb")) == NULL)
{
fprintf(stderr,"Couldn't open the file. ");
exit(EXIT_FAILURE);
}
printf("Type a date (mm-dd-yyyy) or (mm/dd/yyyy): \n");
if(fscanf(fp,"%d%*[/-]%d%*[/-]%d",&m,&d,&y) != 3) //store characters in variables
{
fprintf(stderr, "Not properly formatted.");
exit(EXIT_FAILURE);
}
printf("%s %2d, %4d",month(m),d,y);
return 0;
}
輸入:
01/30/1990
輸出:
Couldn't open the file.
你是如何調用編譯好的程序的? – 2016-09-25 00:23:29
我使用的代碼塊ide,我在程序參數窗口中鍵入01/30/1990,我也用gcc來運行它,它說「系統不能接受你輸入的日期」。 「所需特權不由客戶持有」。 – tadm123
'fopen(「01/30/1999」,「rb」)'會嘗試打開一個路徑爲'01/30/1999'的文件。顯然,不存在這樣的文件。 – 2016-09-25 00:27:36