Why doesn't pressing enter return '\n' to getch()?

前端 未结 9 1664
忘掉有多难
忘掉有多难 2020-12-06 07:43
#include 
#include 
main()
{
    char ch,name[20];
    int i=0;
    clrscr();
    printf(\"Enter a string:\");
    while((ch=getch())!=         


        
相关标签:
9条回答
  • 2020-12-06 08:25

    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.

    0 讨论(0)
  • 2020-12-06 08:27

    The actual meaning of \n is \r+\n. getch() function reads a character from the keyboard.
    It does not echo it and does not wait for next character.
    So whenever we enter \n character getch() function reads \r character only.

    0 讨论(0)
  • 2020-12-06 08:28

    That is because the return key on your keyboard is represented internally as '\r' not '\n'. In order for that specific example to work, you would need to trap '\r' instead.

    0 讨论(0)
  • 2020-12-06 08:30

    Use '\r' and terminate your string with '\0'.

    Additionally, you might try to use getche() to give a visual echo to the user and do some other general corrections:

    #include <stdio.h>
    #include <conio.h>
    
    #define MAX_NAME_LENGTH 20
    
    int main()
    {
        char ch, name[MAX_NAME_LENGTH];
        int i=0;
        clrscr();
        printf("Enter a string:");
        while ( ((ch=getche())!='\r') && (i < MAX_NAME_LENGTH - 1) )
        {
            name[i]=ch;
            i++;
        }
        name[i] = '\0';
        printf("%s\n",name);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-06 08:33

    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
    
    0 讨论(0)
  • 2020-12-06 08:35

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

    0 讨论(0)
提交回复
热议问题