【问题标题】:using fgetc to ignore words after space使用 fgetc 忽略空格后的单词
【发布时间】:2019-12-08 14:46:48
【问题描述】:

我正在使用 txt 文件中的 fgetc 字符串。 在实际字符串之前,该行可以包含许多空格。 在字符串之后,单词之间不应有空格。

welcome //vaild
       hello  //valid
  hello friend //invalid

这是我尝试过的方法

int main(int argc, char **argv)
{
  FILE *file = fopen("test.txt", "r");
  if (!file)
    return -1;
  char input;
   while ((input = fgetc(file)) != EOF)
   {
     if(input == ' ')
     {
       if (input + 1 != '\n' || input +1 != EOF)
       {
          printf("wrong\n");
       }
     } 
   }
   return 0;
}

代码为“hellofriend”字符串打印“错误”,但如果有效字符串之前有空格,它也会打印“错误”。有人可以告诉我如何修改我的代码吗?

【问题讨论】:

  • 你认为input + 1 在你的代码中做了什么?
  • 我想“错误”应该是“错误”?
  • input 应该是 int 以便 EOF 可以适应
  • 另外,您在任何地方都无法使用fgets。只有fgetc。为什么要写fgets 并用它来标记它?
  • 仔细阅读C language上的文档。您可能想使用sscanfstring functions

标签: c string file


【解决方案1】:

你可能想把你的主循环改写成这样:

char current, previous = 0;
while ((current = fgetc(file)) != EOF) {
    if( current == '\n' ) {
        if( previous == ' ' ) {
            printf( "wrong\n" );
        }
    }
    previous = current;
}

好的,这是一个不同的状态机,它忽略前导空格并检测单词之间或行尾的空格:

char leading_spaces = TRUE;  // define this somewhere else
while ((ch = fgetc(file)) != EOF) {
    if( ch == '\n' ) {
        leading_spaces = TRUE;
        continue;
    }
    if( ch == ' ' ) {
        if( !leading_spaces ) {
            printf( "wrong\n" );
        }
    } else {  // non-space, not the leading spaces
        leading_spaces = FALSE;   // define this one as well
    }
}

【讨论】:

  • 如果第一行如下所示,则代码不会打印错误:“错误字符串”单词之间不应有空格
  • 这无法检测到EOF
猜你喜欢
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多