为什么不pressing进入回报的'\\ n'来参考getch()? [英] Why doesn't pressing enter return '\n' to getch()?

查看:84
本文介绍了为什么不pressing进入回报的'\\ n'来参考getch()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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);
}

当我给ABC输入,如果我preSS进入它不工作。任何人都可以让我知道为什么条件CH =残培()!='\\ n'是不是变得虚假,当我preSS进入?我还观察到CH正在\\ r而非\\ n个。请让我知道。谢谢

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

推荐答案

使用'\\ r'和以'\\ 0'终止字符串。

此外,你可以尝试使用getche()得到视觉回声给用户,并且做一些其他的一般更正:

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;
}

这篇关于为什么不pressing进入回报的'\\ n'来参考getch()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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