在C中从命令行和控制台(STDIN)获取输入

在C中从命令行和控制台(STDIN)获取输入,c,C,我是一名编码初学者,很难从命令行和控制台(STDIN)获取输入。我的程序应该搜索并替换字符串中的一组字符。例如,concatenate cat gat:输出必须是congatenate 这是到目前为止我的代码 #include <stdio.h> #include <string.h> #include <stdlib.h> /*Function to replace a string with another string*/ char *rep_str

我是一名编码初学者,很难从命令行和控制台(STDIN)获取输入。我的程序应该搜索并替换字符串中的一组字符。例如,concatenate 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;
}
#包括
#包括
#包括
/*函数将一个字符串替换为另一个字符串*/
char*rep_str(const char*s,const char*old,const char*new1)
{
char*ret;
int i,计数=0;
int newlen=strlen(new1);
int oldlen=strlen(旧);
对于(i=0;s[i]!='\0';i++)
{
if(strstr(&s[i],old)==&s[i])
{
计数++;
i+=oldlen-1;
}
}
ret=(char*)malloc(i+count*(newlen-oldlen));
if(ret==NULL)
退出(退出失败);
i=0;
而(*s)
{
if(strstr(s,old)==s)//将子字符串与新闻字符串进行比较
{
strcpy(&ret[i],新1);
i+=newlen;//将newlength添加到新字符串
s+=oldlen;//将相同的旧长度添加到旧字符串中
}
其他的
ret[i++]=*s++;
}
ret[i]='\0';
返回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);
免费(newstr);
返回0;
}
至于现在,它显示了控制台输入或命令行输入的正确输出,但不是两者都正确


请建议所做的更改

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

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

$ cat file.txt | yourprogram

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


对你的问题一定要明确,并展示你已经尝试过的东西,这样回答起来就很模糊了。你为什么不发布你的程序到底在做什么?你的程序中没有命令行处理。你到底如何调用你的程序?请在你的问题中说清楚。
// 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
}