快速编辑:这是一个家庭作业。我的目标是为我的程序引入一些cl参数(可以是-s,-w,宽度长度,以及文件),并根据默认的40个字符长度对文件进行word包装,如果用户选择了'-w'选项,则使用新的数字。
我试图编写一个C程序,通过命令提示符接收参数(可执行文件名为“wrapfile.exe”)。这个程序还没有完成,还需要添加更多内容,这只是其中的一部分,它正在给我造成伤害。
下面是一个有效的命令提示符条目示例:
C:\"within wrapfile.exe's directory"> wrapfile -s filename.txt
C:\"within wrapfile.exe's directory"> wrapfile -w 5 filename.txt
C:\"within wrapfile.exe's directory"> wrapfile -s -w 50 filename.txt
等。
无效条目示例:
C:\"within wrapfile.exe's directory"> wrapfile
C:\"within wrapfile.exe's directory"> wrapfile -w
C:\"within wrapfile.exe's directory"> wrapfile qwer
等。
我的问题是在我输入“-w”后它无法检测到号码。。
代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "string.h"
int main(int argc, char *argv[])
{
int output = 0;
int commands = 1;
int wraplength= 41;
int i=0;
int counter=0;
int wordwrap = 0;
int ExitStatus = 1;
int input = 1;
int w = 0;
int s = 0;
FILE *f = NULL;
for (i=0; i < argc; i++)
{
if ( (*argv[input] + i-1) == '-') // check for option
{
printf(" - detected first");
if (*(argv[input] + i ) == 's') // check for wordwrap
{
printf(" s detected");
i++;
i++;
s = 1; // set s to true to that option can be added later
wordwrap = 1; // set wordwrap on or true
}
if (*(argv[input] + i) == 'w')//if the second option is a w
{
i++;
printf(" w detected ");
sscanf ((argv[input] + i), "%d", &wraplength);
printf ("%d", wraplength);
if ( wraplength < 1) // check what the number is
{
printf("Usage: wrapfile [-s] [-w width] file ...");
return 2; // command line options incorrect
}
}
if (*(argv[input] + i) == '-')
{
printf(" second - detected");
i++;
if (*(argv[input]+ i) == 'w')//if the second option is a w
{
i++;
if (sscanf ((argv[(input)+1]), "%d", &wraplength) != 1) // check what the number is
{
printf("Usage: wrapfile [-s] [-w width] file ...");
return 2; // command line options incorrect
}
}
}
}
}
return 0;
}
大编辑:
我采纳了迪特里希的Epp建议,这里是我做的一些事情。每次我试图检查“-s”后的参数时,我的程序似乎都会崩溃。我如何检查下一个参数(如果没有?)不会破坏我的程序。我知道这条线和撞车有关:
arg = argv[i++];
代码如下:
while (i < argc)
{
arg = argv[i++];
if (!strcmp(arg, "-s"))
{
arg = argv[i++];
son = 1;
printf("Have -s\n");
if (!strcmp(arg, "-w"))
{
if (i >= argc)
{
printf("Usage: wrapfile [-s] [-w width] file ...");
}
param = argv[i++];
wraplength = *param;
printf("Have -w %s\n", param);
}
}
最佳答案
我认为你把循环变量混入这里。
这使得i
循环覆盖所有参数,包括通常不需要的argv[0]
。
for (i=0; i < argc; i++)
它使用
i
作为一个参数字符串的索引,但语法很有趣。if (*(argv[input] + i ) == 's')
在其他系统上,您只需使用
getopt()
,但在Windows上这并不总是一个选项。建议
你需要这样的循环:
// Note: C99, so you will need to translate to C89 if you use Microsoft's
// C compiler
int i = 1;
while (i < argc) {
char *arg = argv[i++];
if (!strcmp(arg, "-s")) {
printf("Have -s\n");
} else if (!strcmp(arg, "-w")) {
if (i >= argc)
error();
char *param = argv[i++];
printf("Have -w %s\n", param);
} else {
error();
}
}
命令选项解析与程序的性能非常不相关,因此上面的
if
/else
块链和strcmp()
都很好。警告!
你不能用这个指定任意的文件名!如果您从
main()
获取参数,它们将被转换为您当前使用的任何代码页,这对于几乎任何目的都是非常糟糕的。(如果你是唯一一个使用这个程序的人,那就没问题了。)为了指定任意文件名,需要调用
GetCommandLineW()
以获取UTF-16中的命令行,然后CommandLineToArgvW()
将其解析为int argc
和wchar_t **argv
。