String input using getchar()

僤鯓⒐⒋嵵緔 提交于 2019-12-05 02:15:22

问题


The following code uses getchar() to accept a line of input.

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

While typing, if I press backspace, shouldn't it also be received by getchar() & stored in the rawString-pointed location? However the output simply shows the final string without any special characters. Could someone explain why?


回答1:


Standard input is (usually) buffered; non-printing characters like backspace are handled by the terminal server, and library functions like getchar() will never see them.

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




回答2:


#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 is Will Work.



来源:https://stackoverflow.com/questions/3659109/string-input-using-getchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!