注册 登录
编程论坛 C++教室

关于while输入的问题

newCpp 发布于 2009-08-31 17:30, 613 次点击
比如我定义了一个 char h[10];的字符数组
我该如何让他在输入完成10个元素后就不能在输入字符了。
这个我该怎么解决,谢谢各位大鸟帮忙照顾一下下新人嘛!!!
谢谢
我试了很多次没有成功。 我晕
4 回复
#2
yuc19876242009-08-31 21:54
cin.get(h,10);
或 cin.getline(j,10);
#3
xufen3402009-09-01 07:53
#include <iostream>
#include<conio.h>
using namespace std;
int main ()
{
    char h[10];
    int i=0;
    char key;
    while(!kbhit())
        {
          key=getch ();
          if((key==27)||(key<0)) break;

          h[i]=key;
          cout<<h[i];
          i++;
          if(i==10) {
              for(int j=0;j<10;j++) {
                  cout<<endl;
                  cout<<h[j];
              }
              cout<<endl;
              i=0;
          }
        }

    return 0;

}
#4
xufen3402009-09-01 08:06
getche是带回显的,就没必要cout了。
#include <iostream>
#include<conio.h>
using namespace std;
int main ()
{
    char h[10];
    int i=0;
    char key;
    while(!kbhit())
        {
          key=getche();
          if((key==27)||(key<0)) break;
          h[i]=key;
          i++;
          if(i==10) {
              for(int j=0;j<10;j++) {
                  cout<<endl;
                  cout<<h[j];
              }
              cout<<endl;
              i=0;
          }
        }

    return 0;
}
#5
xufen3402009-09-01 09:49
给你个api函数写的程序,可以捕捉你的键盘,你就可以捕捉键盘的输入消息。
#include <windows.h>
#include <stdio.h>

VOID ErrorExit(LPSTR);
VOID KeyEventProc(KEY_EVENT_RECORD);

 
int main(VOID)
{
    HANDLE hStdin;
    DWORD cNumRead, fdwMode, fdwSaveOldMode, i;
    INPUT_RECORD irInBuf[128];
    int counter=0;
    //获得标准输入句柄
    hStdin = GetStdHandle(STD_INPUT_HANDLE);
    if (hStdin == INVALID_HANDLE_VALUE)
        ErrorExit("GetStdHandle");
    //保存旧模式
    if (! GetConsoleMode(hStdin, &fdwSaveOldMode) )
        ErrorExit("GetConsoleMode");
     //新输入模式
     fdwMode = ENABLE_WINDOW_INPUT;
     //设置新模式
     if (! SetConsoleMode(hStdin, fdwMode) )
        ErrorExit("SetConsoleMode");
     while (counter++ <= 100) {
           //获取输入
           if (! ReadConsoleInput(
                hStdin,      // input buffer handle
                irInBuf,     // buffer to read into
                128,         // size of read buffer
                &cNumRead) ) // number of records read
            ErrorExit("ReadConsoleInput");
            //根据输入大小,不要64k
            for (i = 0; i < cNumRead; i++) {
                if(irInBuf[i].EventType==KEY_EVENT) KeyEventProc(irInBuf[i].Event.KeyEvent);
            }

     }
     return 0;
}

VOID ErrorExit (LPSTR lpszMessage)
{
    fprintf(stderr, "%s\n", lpszMessage);
    ExitProcess(0);
}
               
VOID KeyEventProc(KEY_EVENT_RECORD ker)
{
    printf("Key event: ");

    if(ker.bKeyDown)
        printf("key pressed:%c\n",ker.uChar.AsciiChar);
    else printf("key released\n");
}
1