从命令行输入输入以及在C中输入控制台(STDIN)

时间:2017-06-27 09:42:14

标签: c

我是编码初学者,难以尝试从命令行和控制台(STDIN)获取输入。我的程序应该从字符串中搜索和替换一组字符。例如,连接cat gat:输出必须是congatenate!

到目前为止,这是我的代码!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*Function to replace a string with another string*/

char *rep_str(const char *s, const char *old, const char *new1)
{
    char *ret;
    int i, count = 0;
    int newlen = strlen(new1);
    int oldlen = strlen(old);

    for (i = 0; s[i] != '\0'; i++)    
    {
        if (strstr(&s[i], old) == &s[i]) 
        {
            count++;
            i += oldlen - 1;
        }
    }
    ret = (char *)malloc(i + count * (newlen - oldlen));
    if (ret == NULL)
        exit(EXIT_FAILURE);
    i = 0;
    while (*s)
    {
        if (strstr(s, old) == s) //compare the substring with the newstring
        {
            strcpy(&ret[i], new1);
            i += newlen; //adding newlength to the new string
            s += oldlen;//adding the same old length the old string
        }
        else
        ret[i++] = *s++;
    }
    ret[i] = '\0';
    return ret;
}
int main(int argc, char*agrv[])
{
    char mystr[100], c[10], d[10];
    scanf("%s", mystr);

    scanf(" %s",c);

    scanf(" %s",d);


    char *newstr = NULL;


    newstr = rep_str(mystr, c,d);
    printf("%s\n", newstr);
    free(newstr);
    return 0;
}

现在,它显示了控制台输入或命令行输入的正确输出,而不是两者兼而有之!

请建议进行更改!

2 个答案:

答案 0 :(得分:0)

不是尝试通过argc和argv解析输入文件,只需通过stdin传递所有输入文件。这意味着您将始终使用scanf来读取输入数据。

在命令行中,您需要使用管道调用,如下所示:

$ cat file.txt | yourprogram

答案 1 :(得分:0)

您可以检查函数argc的变量int main()

// Path of executable file is passed by default so value of 'argc' will be at least 1
if(argc > 1) 
{
   // do stuff to work on input from command line
}else{
   // do stuff to work on input from STDIN
}
相关问题