stdin是否包含回车符(?r)char? [英] Does stdin ever contain a carriage return (\r) char?

查看:304
本文介绍了stdin是否包含回车符(?r)char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SO答案中,我编写了以下代码:

In an SO answer I wrote this code:

char fail_on_eof (int c)
{
    if (c == EOF)
        exit (EXIT_FAILURE);
    return (char) c;
}

void skip_to_next_line (void)
{
    char c;
    do
    {
        c = fail_on_eof (getchar ());
    } while (c != '\n');
}

我想知道是否有任何终端机可能返回'\r'(只要行尾还有'\n' )。

I was wondering whether there are any terminals that may return '\r' (which is covered by the above code as long as there is also a '\n' at end of line).

stdin 是否包含'\r'(在任何平台上)?输入重定向是 stdin 始终以文本模式运行吗?

Does stdin ever contain '\r' (on any platform)? What about input redirection is stdin always working in text mode?

推荐答案

当然,这很容易。您可以从包含该字符的文件中读取,也可以执行类似的操作(在Linux和类似的操作系统下):

Sure, it's easy. You can read from a file containing that character, or you can do something like (under Linux and similar operating systems):

printf "\r" | yourProgram

甚至从允许转义的终端程序中,例如 CTRL-V CTRL-M

Or even from a terminal program that allows escapes, such as CTRL-VCTRL-M.

但是,这不属于C语言的行尾,它订阅了 LF 方法指示行尾。从 C11 7.21.2流/ 2

However, that's not considered end of line in the C world, which subscribes to the LF method for indicating end of line. From C11 7.21.2 Streams /2:


文本流是有序的由行组成的字符序列,每行
包含零个或多个字符以及一个换行符。

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character.

可能必须添加,更改字符,或在输入和输出中删除以符合表示主机环境中文本的不同约定。

Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment.

换句话说,尽管某些系统在底层环境中使用不同 行结束符,其中许多在C环境中进行自动翻译,以确保代码按预期运行。

In other words, although some systems use a different line ending character in the underlying environment, many of them do automatic translation in the C environment to ensure code acts as expected.

这篇关于stdin是否包含回车符(?r)char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆