如何实现puts()函数?

2 c

我尝试实现 put 函数。它实际上返回一个值,但我无法得到它应该返回的值。请检查我的代码并进一步指导我

/* implementation of puts function */
#include<stdio.h>
#include<conio.h>
void puts(string)
{
    int i;
    for(i=0;    ;i++)
    {
        if(string[i]=='\0')
        {
            printf("\n");
            break;
        }
        printf("%c",string[i]);

    }

}
Run Code Online (Sandbox Code Playgroud)

Pau*_*han 6

请参阅代码中的注释。

int puts(const char *string)
{
    int i = 0;
   while(string[i])  //standard c idiom for looping through a null-terminated string
    {
        if( putchar(string[i]) == EOF)  //if we got the EOF value from writing the char
        { 
            return EOF;
        }
        i++;
    }
   if(putchar('\n') == EOF)  //this will occur right after we quit due to the null terminated character.
   {
       return EOF;
   }
   return 1; //to meet spec.
}
Run Code Online (Sandbox Code Playgroud)

而且,顺便说一句 - 我已经编写了 putc 的等效项,在嵌入式系统上进行开发时放置了几个不同的时间。因此,这并不总是只是一种学习练习。:)

对 EOF 的评论:它是来自 stdio.h 的 POSIX 常量。在我的 Linux stdio.h 中,我有这样的定义:

/* End of file character.
   Some things throughout the library rely on this being -1.  */
#ifndef EOF
# define EOF (-1)
#endif
Run Code Online (Sandbox Code Playgroud)

该定义代码是 GPL 2.1。