c - 通过 argv 传递的参数会影响程序的输出

标签 c string argv

这是家庭作业

因此,对于我的项目,我必须将两个字符串组合在一起,其中两个字符串组合时都有一个模式。 (这是相当模糊的,所以我在下面举一个例子。我的问题是我的主函数中的 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/

相关文章:

regex - Powershell:使用 -replace 与正则表达式

c - 使用 main(int argc,char *argv[]) 时出现问题

c - 将 Python/Matlab 移植到 C 和定点 DSP 处理器——C 也应该是定点的吗?

objective-c - 接口(interface)声明了两次? - Objective-C

c - 如何从指针变量计算数组的大小?

java - 创建以字符串命名的对象

c - 有没有办法将 void *buf 转换为 char?

java - 将字符串转换为数字的输出不符合预期

c - C语言中如何通过字符串打开文件

c - 从 argv 中读取数字输入数据并存储到 C 中的 int 数组中