【问题标题】:Splitting scanf input into arrays until EOF将 scanf 输入拆分为数组直到 EOF
【发布时间】:2015-02-01 19:15:42
【问题描述】:

希望使用 scanf 进行阅读,但如果遇到 '、' '\0' (换行符) 或 EOF,我想停止阅读

我不确定如何停止实现这一目标。

我正在使用

 char * aBuff;
 char * bBuff;
 char * cBuff;

 //read in the first three lines and put them into char arrays
 //while (scan() != (',' || '\0' || EOF))  //was trying to put it into a while loop, wasn't sure
 scanf("%s", aBuff);
 scanf("%s", bBuff);
 scanf(%s, cBUff);

我计划获取输入并将它们放入单独的数组中。基本上将输入直到 a 或 new line 并将该数据放入数组中并继续此过程直到文件结束。

【问题讨论】:

    标签: c arrays scanf eof


    【解决方案1】:

    您可以尝试使用scansets

    scanf() 应该在 EOF 上停止,但您可能希望执行以下操作:

    scanf("%[^,\0]", &s);
    

    【讨论】:

    • scanf() 只能看到'\0' 之前的格式。 "%[^,\0]" 将显示为 "%[^,"
    【解决方案2】:

    在遇到',''\0'EOF 之前,scanf() 不是一种实用的阅读方法。使用fgetc()

    最大的问题是以scanf() 的格式指定'\0'。示例:格式为"%[^,\0]"scanf() 仅读取"%[^,",因为它在嵌入的'\0' 处停止。所以使用无效的格式说明符 --> 未定义的行为。

    size_t ReadX(char *dest, size_t size) {
      size_t len = 0;
      if (size) {
        while (--size > 0) {
          int ch = fgetc(stdin);
          if (ch == 0 || ch == ',' || ch == EOF) break;  // maybe add \n too.
          *dest[len++] = ch;
        }
        *dest[len] = '\0';
      }
      return len;  // or maybe return the stopping ch
    }
    

    scanf() 如果代码使用繁琐,可以使用:

    scanf("%[\1\2\3...all_char_codes_min_char_to_max_char_except_,_and\0]%*c", &s);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多