C语言 如何在c语言中将回车键表示为字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25835901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:22:42  来源:igfitidea点击:

how to represent enter key as char in c Language?

c

提问by Billal.Teiba

I have tried this :

我试过这个:

switch(c)
case 13 : {printf("enter pressed");break;}

and this :

和这个 :

switch(c)
case '\n' : {printf("enter pressed");break;}

but It didn't work out

但它没有成功

回答by JO53JUL10

Try to use '\r'instead. The 'Enter' key represent Carriage Return that is the same as '\r'.

尝试使用'\r'。'Enter' 键代表与 相同的回车'\r'

回答by Abhishek Choubey

"Enter" represents a new line character in C language. So you can use its ascii value i.e. 10 for its representation. Eg :

“回车”在 C 语言中代表换行符。所以你可以使用它的 ascii 值,即 10 作为它的表示。例如:

#include<stdio.h> 

Try this code :

试试这个代码:

int main()
{
   char ch = '\n';
   printf("ch = %d\n", ch);
}

Later you can use the following code as a test for switching '/n'

后面可以用下面的代码作为测试切换'/n'

int main()
{
  char ch = '\n';
  switch(ch)
  {
    case '\n' : 
           printf("Enter pressed\n");
    break;
    default : 
       //code
  }
}

回答by Magnus Hoff

This program reads from standard input and writes "enter pressed" whenever a newline occurs in the input:

该程序从标准输入读取并在输入中出现换行符时写入“按下输入”:

#include <stdio.h>

int main()
{
    int c;

    for (;;) {
        c = getc(stdin);
        switch (c) {
        case '\n':
            printf("enter pressed\n");
            break;
        case EOF:
            return 0;
        }
    }
}

I think this is what you are looking for.

我想这就是你要找的。

You might be missing the trailing \nin your printf-call, causing the message to be buffered for output but maybe not flushed so it appears on the screen.

您可能忽略尾随\n在你printf-call,使其得到缓冲的消息输出,但也许不会被刷新,使其显示在屏幕上。