为什么按回车键不返回 ' ' 到 getch()? [英] Why doesn't pressing enter return ' ' to getch()?

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

问题描述

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

当我输入abc"时,如果我按回车,它就不起作用.谁能告诉我为什么当我按 Enter 时条件 ch=getch() != ' ' 不会变成假?我还观察到 ch 正在使用 而不是 .请让我知道.谢谢

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() != ' ' is not becoming false when I press enter? I have also observed that ch is taking instead of . Kindly let me know. Thanks

推荐答案

使用 ' ' 并用 '' 终止您的字符串.

此外,您可能会尝试使用 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())!='
') && (i < MAX_NAME_LENGTH - 1) )
    {
        name[i]=ch;
        i++;
    }
    name[i] = '';
    printf("%s
",name);

    return 0;
}

这篇关于为什么按回车键不返回 ' ' 到 getch()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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