【发布时间】:2016-09-26 04:57:13
【问题描述】:
我在使用这个程序时遇到了问题,当我使用标准输入时它运行良好,但当我修改它以从命令行获取字符时它没有。我知道我做错了什么,但不知道是什么,任何帮助将不胜感激。
描述和代码:
/* 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.
【问题讨论】:
-
我正在使用代码块 ide,我在程序参数窗口中输入了 01/30/1990,我还使用 gcc 运行它,它显示“系统无法接受您输入的日期”。 “客户不拥有所需的特权”。
-
fopen("01/30/1999","rb")将尝试打开路径为01/30/1999的文件。显然,不存在这样的文件。 -
argv[1]具有未定义的行为,除非您之前确定argc至少为两个。 -
不要在
fp上使用fscanf(file-scanf),而是在argv[1]上使用sscanf(string-scanf)。 -
不要使用
fprintf(stderr,"Couldn't open the file. ");(它会产生几乎无用的错误消息),试试perror( argv[1]),它会告诉你问题出在哪里。