How can I detect a space or newline at the end of scanf()?

好久不见. 提交于 2020-01-24 10:17:27

问题


I'm writing a program where I have to accept commands from the user like a shell where the user can set values for environment variables. The problem I'm having is if the user types set var var-value I need to know the user typed a space instead of just set and pressed enter which is a different command. How can I determine if the user pressed space or enter using scanf()?


回答1:


You'll know the user pressed enter because scanf() won't return until the user does so. If you're trying to read characters in real time as the user types, scanf() will not work for you. You will need to use the getchar(), getch() or getche() functions, or a function provided by the OS for reading keyboard input. Read the characters one by one into an array, scanning for spaces and the enter key as you read.

See also this question.




回答2:


You would use fgets instead of scanf




回答3:


You can check with isspace() function in ctype.h

Another way you can use strchr() to find whether input consists '\n' or space

if(strchr(input,'\n')==NULL && strchr(input,' ')==NULL)
{
//do something
}  

EDIT

scanf() reads input till occurrence of any white space character. After white space ignores input.

Use fgets() Instead of scanf() if you enter input of length less than MAXLENGTH , '\n' stays before Null character

Replace it with null character

char input[MAXLENGTH+1];  

fgets(input,sizeof(input),stdin);

if(input[strlen(input)-1]=='\n')     
input[strlen(input)-1]='\0'; 



回答4:


How can I detect a space or newline at the end of scanf()?

Use %[\n] to read input upto a '\n'.

char buffer[256];
//                  v------- Read and discard leading whitespace
int retval = scanf(" %255[\n]", buffer);
if (retval != 1) {
  ; // handle error or EOF
}
// Now scan buffer for whatever input format you desire
char ch;
retval = sscanf(buffer, "set%c", &ch);
if ((retval == 1) && (ch == '\n')) {
  ; // deal with "set"
}
else {
  char var[256];
  char value[256];
  retval = sscanf(buffer, "set %s %s", var, value);
  if (retval == 2)  {
    ; // deal with "set var var-value"
  }
  else {
  // other parsings
  }
}


来源:https://stackoverflow.com/questions/18989439/how-can-i-detect-a-space-or-newline-at-the-end-of-scanf

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