String input using getchar ()

The following code uses getchar () to receive an input line.

#include <stdio.h>
#include <stdlib.h>

int main()
{
 char *rawString = (char *)malloc(200*sizeof(char));
 char *rawStringInitial = rawString;
 char c;
 c=getchar();
 while(c!='\n')
 {
  *rawString=c;
  rawString++;
  c=getchar();
 }
 *rawString='\0';
 printf("\n[%s]\n",rawStringInitial);
 return(0);
}

When typing, if I press backspace, should I also not get getchar () it and store it in the place specified in rawString? However, the output simply displays the final line without any special characters. Can someone explain why?

+3
source share
2 answers

Standard input is (usually) buffered; non-printable characters, such as backspace, are processed by the terminal server, and library functions, such as getchar(), never see them.

If you need to read raw keystrokes, you will need to use something outside of the C standard library.

+5
source
#include<stdio.h>     
#include<conio.h>
#include<string.h>

void get_string(char *string);

void main(){
char *stringVar;
clrscr();
printf("Enter String : ");
get_string(stringVar);
printf("String Enter : %s",stringVar);
getch();
}

void get_string(char *string){
char press;int i=0;
do{
press=getch();
  if(press!=8){
  printf("%c",press);
  string[i]=press;
  i++;
  }
  else if(i>0){printf("\b%c\b",0);sting[i]=NULL;i--;}
}while(press!13);
}

This will work.

0
source

Source: https://habr.com/ru/post/1763614/


All Articles