首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用getchar函数创建一个gets函数,该函数在return pressed时返回char*

使用getchar函数创建一个gets函数,该函数在return pressed时返回char*
EN

Stack Overflow用户
提问于 2018-07-20 02:31:51
回答 1查看 69关注 0票数 -2

我遇到这个问题有一段时间了。我不能创建允许用户使用get_char()函数获取maxChar*的get (Int Char)函数。

我当前的代码:

代码语言:javascript
复制
char* gets(int maxChar) {
    char a;
    char* b;
    int i;
    for(i = 0; i<maxChar; i = i + 1){
        a = getchar();
        if (a != 0x0D) {putchar(a);} else {puts("\r\n");break;}
        b[sizeof(b)] = a;
    }
    if (sizeof(b) > maxChar-1) {puts("\r\n");}
    return b;
    //if (b[sizeof(b)-1] != '')
}

get_char()函数可以完美地工作。

完整内核。c:https://pastebin.com/3bqTbHsv

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-20 03:04:52

下面是对你试图做的事情的一个有根据的猜测。它包含了一些解释,以及一个调用示例:

代码语言:javascript
复制
char* _gets(int maxChar) // change name to avoid conflict with library 'gets'
{
    //char a; //addresses concern pointed out in comments. 
    int a;    //variable is used by function that can return EOF (-1)
    int i=0; //

    char* b = calloc(maxChar + 1, 1);//point pointer to memory (that it owns)
    if(b) //test for success before going on
    {
        for(i = 0; i<maxChar-3; i = i + 1) // -3 to leave room for \r\n\0
        {

            a = getchar();
            if ((a != 0x0D) && (a != EOF)) 
            {
                putchar(a);
                b[i]=a;// place char into string accumulator
            }
            else break;// either EOF or <ENTER> occurred 

        }   // no need for else in this implementation as we can handle
            // the clean up once the conditions are met by outputting 
            // user's entries, then preparing your string (array) for return
        puts("\r\n");
        b[i++]='\r';
        b[i++]='\n';
        b[i++]='\0';
    }
    else return NULL;//failed to allocate memory.  leave

    return b;  // return  b (now a string)
    //if (b[sizeof(b)-1] != '')  // not sure what this was for
}

int main(void)
{ 
    char *strArray = _gets(10);//creates memory for strArray
    if(strArray) //use only if not NULL
    { 
        printf("The array contains: %s", strArray );
        free(strArray );
    }

    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51429636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档