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

前端 未结 9 1711
忘掉有多难
忘掉有多难 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: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 
    #include 
    
    #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;
    }
    

提交回复
热议问题