这是家庭作业
因此,对于我的项目,我必须将两个字符串组合在一起,其中两个字符串组合时都有一个模式。 (这是相当模糊的,所以我在下面举一个例子。我的问题是我的主函数中的 argv 参数。argv 在程序运行时读取用户的输入。所以它就像 ./program_name -r 。 -r 对于程序的这一部分将使其成功,因此下面显示的示例将在用户输入后运行。但是我遇到的问题是,如果我有任何其他字母,例如 -d 那么程序仍然运行。这不会是问题,但我的程序的另一部分要求我有不同的运行代码,以便程序会做不同的事情。我认为我的问题在我的 if 语句中,但我不明白为什么它不起作用.任何帮助将不胜感激!
输入:字符串1:abc
字符串 2:123
输出:a1b2c3
这是我的程序,它符合要求并给出正确的输出
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void merge(char *s1, char *s2, char *output)
{
while (*s1 != '\0' && *s2 != '\0')
{
*output++ = *s1++;
*output++ = *s2++;
}
while (*s1 != '\0')
*output++ = *s1++;
while (*s2 != '\0')
*output++ = *s2++;
*output='\0';
}
int main(int argc , char *argv[])
{
int i;
if(argv[i] = "-r") {
char string1[30];
char string2[30];
printf("Please enter a string of maximum 30 characters: ");
scanf("%s" ,string1);
printf("Please enter a string of maximum 30 characters: ");
scanf("%s" ,string2);
char *output=malloc(strlen(string1)+strlen(string2)+1);
//allocate memory for both strings+1 for null
merge(string1,string2,output);
printf("%s\n",output); }
return 0; }
最佳答案
C8263A20 已经回答了您犯的错误,但比较字符串并不是这样做的。
注意:解析命令行选项是一项相当复杂的任务,如果可能的话,您应该使用现成的解决方案,例如:getopt(3)
(在 Posix 中)!
针对您当前问题的简短且(严重过度)简化的解决方案是:
#include <stdio.h>
int main(int argc, char *argv[])
{
// check: do we have one option given at all?
if (argc == 2) {
// first character is a hyphen, so skip it
// A good idea would be to check if the assumption above is correct
switch (argv[1][1]) {
// we can only "switch" integers, so use single quotes
case 'r':
puts("Option \"r\" given");
break;
case 'd':
puts("Option \"d\" given");
break;
default:
printf("Unknown option %c given\n", argv[1][1]);
break;
}
} else {
puts("No options given at all");
}
return 0;
}
如果您这样做(使用开关
),您可以轻松添加更多单字母选项,而不会弄乱您的代码。将其放入循环中,您可以立即为程序提供更多选项。
关于c - 通过 argv 传递的参数会影响程序的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47613486/