Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

Cursor positioning by using arrow keys for getch in C

I am very beginner in C and would like to code something which gets name from user and rearrange it with backspace, cursor(by using arrow keys).

In the program, when user writes his name and press ESC it has to stop the program and print the name on the screen.

So far, I was able to do ESC and Backspace parts with usign getch() and their ASCII codes, but I'm having problem on moving cursor by using arrow keys when user tries to rewrite or rearrange his name.

Here is my code:

#include<stdio.h>
#include<conio.h>

int main() {
  int i, k = 0;
  char character;
  char samplearray[100];

  printf("Enter your name:
");

  while (1) {
    character=getch();

    if (character != 0x1B && character != 0x8 && character != 0x4B) {
      samplearray[k] = character;
      k++;
      printf("%c", character);
    }

    else if (character == 0x8) {        //Deleting procces in name and it works without any problem.
      samplearray[k];
      k--;
      system("cls");
      printf("Enter your name:
");
      for (i = 0; i <= k; i++) {
        printf("%c", samplearray[i - 1]);
      }
    }

    else if (character == 0x4B) {        //Having a problem on this part.
      samplearray[k] = character;
      k--;
      printf("", samplearray[k]);
    }

  else
    break;
  }
  printf("
Your name is: 
");
  for (i = 0; i <= k - 1; i++) {
    printf("%c", samplearray[i]);
  }
  getch();
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...