当空格应该被忽略时,我应该如何读取C中的一个字符?

时间:2014-01-13 21:28:58

标签: c

我应该用C创建一个函数,它读取一个char并返回它。如果读取失败,该函数应返回0。函数应忽略空格字符。如果给定char是'',则应该读取下一个下一个char,直到给出非空格char。

我已经知道scanf忽略了空格,因此无法使用。我使用getchar如何才能知道读取是否失败?有什么想法吗?

3 个答案:

答案 0 :(得分:2)

在阅读字符的情况下,

scanf不会跳过空格(空格)。要在不阅读空格的情况下使用scanf,您可以执行以下操作:

scanf(" %c", ch) // ch is char type  
       ^Notice the space before %c.  

要使用getchar,您必须检查空格

int ch;
while((ch = getchar) != EOF)   // This will also check the reading failed by getchar.
{
    if(ch == ' ')
        continue;
    ...
}    

答案 1 :(得分:1)

如果您需要忽略' ''\t'\n'等空白区域,请使用" %c"中的scanf(),如@haccks所建议的那样,并使用scanf()的返回值来确定成功。

int Read1_NotWhiteSpace(char *ch) {
  int retval = scanf(" %c", ch);
  if (retval == 1) return 1;
  return 0; // fail
}

如果您只需要忽略' '(空格),请使用int getchar(void)

int Read1_NotSpace(char *ch) {
  int c;
  while ((c = getchar()) == ' ');
  if (c == EOF) return 0; // fail
  *ch = (char) c;
  return 1;
}

注意:OP不清楚如何成功返回。可以在成功时返回ch,但无法区分罕见的'\0'读数。以下简单回报ch成功。

int Read1_NotSpaceAlternate(void) {
  int c;
  while ((c = getchar()) == ' ');
  if (c == EOF) return 0; // fail
  return c;
}

答案 2 :(得分:0)

如果getchar失败,则返回EOF,通常为-1。