我正在开发自己的多行输入功能,无法在我想要的时候终止

时间:2015-01-11 06:39:49

标签: c fgets strcmp multilinestring

我正在尝试制作一个函数,它将指针指向一个字符数组,它的大小和1作为争论。

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

#define FIRST_LINE 1
#define DONE 2
#define MORE_LINES 3
#define EXTRA 4

int a_fun(int, char *, size_t);

main()
{
char que[20];
int status=0;
status=a_fun(FIRST_LINE,que, sizeof(que));
fputs(que,stdout);

printf("\nStatus:\t %d\n",status);

return 0;
}


int a_fun(int lnum, char *str, size_t sz)
{

    char *temp, ch, *end="!exit";
    if(lnum==FIRST_LINE)
    {

        if (fgets (str, sz, stdin) == NULL)
        {
            printf("\nEntered nothing at all. (Type !exit to terminate)\n");
            return FIRST_LINE;
        }
        for(;(*str!='\0'||*end!='\0');str++,end++)
        {
            if(!*str) if(!*end) return DONE;
        }

        if(strlen(str)>=sz)
        {
            while((ch=getchar())!='\n'); //cleaning buffer
            return EXTRA;
        }
        return MORE_LINES;
    }
}

我想通过输入&#34;!退出&#34;退出输入但我无法做到这一点。我尝试使用if(strcmp(str,"!exit")==0) return DONE;if(str=="!exit") return DONE;执行此操作 最后,我尝试比较两个角色,但都是静脉。请尝试给我一些解决方案
要输入更多行,我们可以在a_fun()中使用条件块,所以基本上现在它只是一个行输入函数而我的问题是在它们之间终止输入过程(如果它进入多个线状态。)
如果你能给我任何关于使这个功能更安全的建议,除了我原来的问题,我将不胜感激,因为我将在我的网站的CGI代码中使用这个功能。

2 个答案:

答案 0 :(得分:2)

if(strcmp(str,"!exit")==0)

这不起作用,因为fgets()在输入的末尾添加换行符,您必须小心地用\n in-oder替换\0以执行上述检查

答案 1 :(得分:0)

谢谢@Gopi现在我解决了我的问题:

        while(1)
        {
            if((*end=='\0')&&(*str=='\n')) return DONE;
            if((*end!=*str)||(*end=='\0')) break;
            end++;
            str++;
        }

另一种解决方案是:

    char end[]={'!','e','x','i','t','\n'};
    if(strcmp(str,end)==0) return DONE;