gpt4 book ai didi

c - 在 C 中处理 stdin 上的输入

转载 作者:行者123 更新时间:2023-11-30 15:41:10 25 4
gpt4 key购买 nike

我是新来的@programming,我有以下问题:我的程序启动命令提示符:如

input>

然后用户输入一个字符串,一个类似 merge xyz.txt 的命令我终于让它运行了,我的程序只从开始读取到 space 。所以

printf("%s", command);

output: merge

如果用户输入一个字符串,其中该命令不是命令或没有值,则应重新开始打印 input>并且在命令完成后,它应该打印 input>再次。我尝试将所有内容放入 while 循环中:

void cmdLine()
{
char *whole_entrie = calloc(1,1);
char buffer[BUFFERSIZE];
int dummy = 0;
while(dummy == 0)
{
printf("input>");
fgets(buffer, BUFFERSIZE, stdin);
whole_entrie = realloc(whole_entrie, strlen(buffer) + 1);
strcpy(whole_entrie, buffer);
strcpy(buffer, ""); //reset because i thought the programm uses old entries?????ß

int cnt = 0;
char command[MAX_COMMAND_LENGTH];

while(cnt <= MAX_COMMAND_LENGTH)
{
if(whole_entrie[cnt] == ' ')
{
break;
}
else
{
command[cnt] = whole_entrie[cnt];
cnt++;
}
}

if(strcmp(command, "merge") == 1)
{
merge();
}
else if(strcmp(command, "close") ==1)
{
free(whole_entrie);
dummy = 1;
}
但是:它随机地做其他事情。有时我会遇到双重释放错误,或者他返回 0 或者显示 printf()merge当我输入 xxxkdlf等等,有人可以帮助我吗,我对这个该死的代码感到沮丧!!!

问候

最佳答案

你为什么要使用realloc()?我在这里看不到动态分配的任何理由。为什么不能只处理 buffer 内容?

符合C99标准:

7.19.7.2 The fgets function Synopsis

...

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

还有一点。为什么这么奇怪的 memcmp() 调用?来自man memcmp:

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

好吧,终于(也许)第三了。您检查 whole_entrie 内是否有空格('')以停止。但是,如果您只是在末尾输入带有 '\n' 的命令,您将复制它,其中包括 '\n',因此 strcmp() 将失败检查您的命令。

关于c - 在 C 中处理 stdin 上的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com