Print to stdout without `printf`, `puts`, `putchar`, etc

huangapple go评论46阅读模式
英文:

Print to stdout without `printf`, `puts`, `putchar`, etc

问题

#include <stdio.h>

int _putchar(char c)
{
    return 0;
}

int main()
{
    _putchar('_');
    _putchar('p');
    _putchar('u');
    _putchar('t');
    _putchar('c');
    _putchar('c');
    _putchar('h');
    _putchar('a');
    _putchar('r');
    _putchar('\n');
    return(0);
}

Expected output is:

_putchar
英文:

Please, how can I make my main() function print out the inputs, by calling a function named _putchar()?

We are not allowed to use built-in functions like printf(), puts(), putchar(), etc.

The instructions are as follows:

> - You are not allowed to use the standard library. Any use of functions like printf, puts, etc… is forbidden
>
> - You are allowed to use _putchar

Apparently, we are only allowed to create our own function, which can then be called to our main output.

Here is my code below:

#include &lt;stdio.h&gt;

int _putchar(char c)
{
    return 0;
}
int main()
{
    _putchar(&#39;_&#39;);
    _putchar(&#39;p&#39;);
    _putchar(&#39;u&#39;);
    _putchar(&#39;t&#39;);
    _putchar(&#39;c&#39;);
    _putchar(&#39;c&#39;);
    _putchar(&#39;h&#39;);
    _putchar(&#39;a&#39;);
    _putchar(&#39;r&#39;);
    _putchar(&#39;\n&#39;);
    return(0);
}

Expected output is:

> _putchar

答案1

得分: 2

你可能需要使用类似于POSIX系统上的write系统调用或其他平台上类似的方法来实现_putchar

#include <unistd.h>

int _putchar(char c)
{
    return write(1, &c, 1) == 1 ? c : -1;
}
英文:

You might be expected to implement _putchar using a system call such as write on POSIX systems or something similar on other platforms:

#include &lt;unistd.h&gt;

int _putchar(char c)
{
    return write(1, &amp;c, 1) == 1 ? c : -1;
}

答案2

得分: 1

以下是您的答案:

#include <stdio.h>

int _putchar(char c)
{
    int n = 0;
    n = write(1, &c, 1);
    return n;
}

int main()
{
    int m = 0;
    m = _putchar('_');
    m = _putchar('p');
    m = _putchar('u');
    m = _putchar('t');
    m = _putchar('c');
    m = _putchar('c');
    m = _putchar('h');
    m = _putchar('a');
    m = _putchar('r');
    m = _putchar('\n');
    return 0;
}
英文:

Here is my answer:

#include &lt;stdio.h&gt;

int _putchar(char c)
{
    int n = 0;
    n = write(1,&amp;c,1);
    return n;
}

int main()
{
    int m = 0;
    m = _putchar(&#39;_&#39;);
    m = _putchar(&#39;p&#39;);
    m = _putchar(&#39;u&#39;);
    m = _putchar(&#39;t&#39;);
    m = _putchar(&#39;c&#39;);
    m = _putchar(&#39;c&#39;);
    m = _putchar(&#39;h&#39;);
    m = _putchar(&#39;a&#39;);
    m = _putchar(&#39;r&#39;);
    m = _putchar(&#39;\n&#39;);
    return(0);
}


huangapple
  • 本文由 发表于 2023年6月22日 07:09:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定