Why doesn't pressing enter return '\n'

2019-01-15 03:17发布

#include <stdio.h>
#include <conio.h>
main()
{
    char ch,name[20];
    int i=0;
    clrscr();
    printf("Enter a string:");
    while((ch=getch())!='\n')
    {
        name[i]=ch;
        i++;
    }
    name[i] = '\0';
    printf("%s",name);
}

When I give "abc" as input and if I press enter it's not working. Can anyone let me know why the condition ch=getch() != '\n' is not becoming false when I press enter? I have also observed that ch is taking \r instead of \n. Kindly let me know. Thanks

标签: c input
9条回答
聊天终结者
2楼-- · 2019-01-15 03:24

Try \r instead of \n

\n is the new line character (0x0A) or 10 decimal, \r is the carrige return character (0x0D) or 13 decimal.

The return key is a carrige return.

查看更多
三岁会撩人
3楼-- · 2019-01-15 03:24

on some system the newline is "\r\n" carriage return (enter) is "\r"

查看更多
戒情不戒烟
4楼-- · 2019-01-15 03:28

The keyboard return key is the carriage return, or CR. This is found by running the program and analyzing the results.

When you press enter key, the ASCII value of Enter key is not returned, instead CR is returned.

Hence (ch=getch())!='\n' should be changed to any of the following equivalent statements:

ch=getch())!='\r' 
ch=getch())!=13     // ASCII for CR: decimal
ch=getch())!=0xd     // hexadecimal for CR
ch=getch())!=0xD     // hexadecimal for CR
ch=getch())!=015     // octal for CR
查看更多
聊天终结者
5楼-- · 2019-01-15 03:30

I think it would be better to simply use:

scanf("%19s", name);

instead of getch thing.

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-15 03:32

It depends on your system. Also you must know that getch() it's a part of the XSI Curses Standard issued by X-Open or OpenGroup and not related to the Borland specific conio.h header.

You must use getchar(3) or getc(3), which all of them belong to the ISO/IEC 9899:1990 standard. Both calls retreives just one byte from the controlling terminal/console or the input stream, respectively.

If you are calling them from a Windows platform, you retreive with the Enter key, the '\r', '\n' sequence, instead of just '\n'. Then you must create a loop arround the getchar(3) or getc(3) calls. Also, a call to fgets(3) over stdin would work to obtain the '\r', '\n' sequence.

Another point, is that some platforms needs flush the stding stream, then you must apply the fflush(3) call to the stdin stream.

fgets(3) and fflush(3) belongs to the ISO/IEC 9899:1990 standard.

查看更多
▲ chillily
7楼-- · 2019-01-15 03:35

An enter is actually "\r\n" (carriage return and line feed) on Windows. getchar() will return '\n' I think.

查看更多
登录 后发表回答