使用getc从控制台读取\ r(回车)vs \ n(换行)? [英] Reading \r (carriage return) vs \n (newline) from console with getc?

查看:469
本文介绍了使用getc从控制台读取\ r(回车)vs \ n(换行)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数,该函数基本上等待用户按下"enter",然后执行某些操作.我发现在测试时有效的内容如下:

I'm writing a function that basically waits for the user to hit "enter" and then does something. What I've found that works when testing is the below:

#include <stdio.h>

int main()
{
        int x = getc(stdin);
        if (x == '\n') {
                printf("carriage return");
                printf("\n");
        }
        else {
                printf("missed it");
                printf("\n");
        }
}

我所遇到的问题以及我最初尝试做的事情是:if (x == '\r'),但是在测试中,该程序并没有使我按Enter键. '\n'似乎与我从控制台中按Enter键相对应.有人可以解释其中的区别吗?另外,要验证,将其写为if... == "\n"表示字符串文字?即用户实际上必须从控制台输入"\n",对吗?

The question I have, and what I tried at first was to do: if (x == '\r') but in testing, the program didn't catch me hitting enter. The '\n' seems to correspond to me hitting enter from the console. Can someone explain the difference? Also, to verify, writing it as if... == "\n" would mean the character string literal? i.e. the user would literally have to enter "\n" from the console, correct?

推荐答案

\n是换行符,而\r是回车符.它们的用途不同. Windows使用\r\n表示按下Enter键,而Linux和Unix使用\n表示按下Enter键.

\n is the newline character, while \r is the carriage return. They differ in what uses them. Windows uses \r\n to signify the enter key was pressed, while Linux and Unix use \n to signify that the enter key was pressed.

因此,我将始终使用\n,因为它被所有人使用.而if (x == '\n')是测试字符相等性的正确方法.

Thus, I'd always use \n because it's used by all; and if (x == '\n') is the proper way to test character equality.

这篇关于使用getc从控制台读取\ r(回车)vs \ n(换行)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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