2017-12-02 116 views
2

此的输出作业参数通过argv的影响,通过该程序

所以对我的项目,我有两个字符串在一个从那里合并当两个字符串有一个模式相结合。 (这非常模糊,所以生病把下面的例子放在下面,我的问题是在我的main函数中使用了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; } 

回答

2

你犯的错误已经被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; 
} 

如果你做这种方式(用switch),您可以轻松地添加更多的单字母选项而不会干扰你的码。把它放在一个循环中,你可以给程序更多的选择。

+0

我正在考虑为这个程序使用switch语句,但我不知道它是如何完成。这帮助了一大堆。谢谢! – chrisHG

1
  1. 我没有初始化
  2. 的argv [ i] =“-r”< - 是一个赋值语句,应该使用“==”
+0

我试过,但是当我有==它只是退出程序 – chrisHG

+0

,因为我没有初始化,所以argv [i]指向完全随机的地方。你想检查argv [1] – Ora

+0

对不起,我也初始化为一个整数值,忘记包括在我的评论 – chrisHG

1

你在你的主函数中要做的是检查第一个命令行参数是否等于“-r”。

你实际上在做什么是通过使用单个'='给argv [i]分配“-r”。 在C中,通过'=='运算符完成比较。

但是,由于您只是比较字符串(它是C中的字符数组),因此您不能使用'=='来达到此目的,因为您只会比较字符数组开始处的地址。

而是使用C库函数strcmp用于此目的:

https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

您还没有初始化的变量i为奥拉已经指出。