c - 如何在c中将文件中的单词与数字分开

标签 c

我需要找到文件中一组数字的反转度数。

我从 .txt 文件中读取输入,格式如下:

SET 1: -3 1 2 0 4
SET 2: 0 1 2 3 4 5
SET 4: 29 39 0 1 3

我不知道如何分离输入(集合及其编号)。我想把它们放在一个结构中,但到目前为止它没有用。 反转度 = 小于其索引值的数字的数量。例如,在 SET 2 中,反转度为 0。

最佳答案

您需要在卡住的地方发布代码;这是获得帮助的最佳方式。 无论如何,这里有一些粗略的代码可以帮助您确定问题出在哪里。我一直保持简单,让您了解 vanilla C 如何执行 I/O。

#include <stdio.h>                   /* snprinf, fprintf fgets, fopen, sscanf */

int main(void)
{
  char line_buffer[64];
  FILE* infile = fopen("yourfile.txt", "r");         /* open file for reading */
  while(fgets(line_buffer, 64, infile) != NULL)
  {
    char set_name[8];                 /* construct a string w/ the set number */
    snprintf(set_name, 8, "SET %c:", *(line_buffer+4));    /* no. is 5th char */
    fprintf(stdout, "%s ", set_name);           /* fprintf w/ stdout = printf */

    int set[8];
    int ind = 0;
    for(int i=7; line_buffer[i]!='\0';)    /* start from first number and end */
    {                       /* when string ends, denoted by the '\0' sentinel */
      int n;    /* using pointer arithmetric, read in and store num & consume */
      sscanf(line_buffer+i, "%d %n", set+ind, &n);     /* adjacent whitespace */
      i += n;               /* n from sscanf tells how many chars are read in */
      fprintf(stdout, "%d ", set[ind]);
      ind +=1;
    }

    fprintf(stdout, "\n");
  }

  return 0;
}

关于c - 如何在c中将文件中的单词与数字分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839157/

相关文章:

c++ - 在 macOS Catalina 上从源代码编译 LLVM(How to solve "stdio.h"not found)

c - 如何修复此 do-while 循环,以便控制台程序在自动关闭之前提示用户?

c - 素数求和给出了错误的答案

c - 如何在不阻塞的情况下同步线程?

c - POSIX 文件锁是否可重入?

c - 如何按值可变大小数组传递(到函数)?

C: 在二进制基础中打印 Unsigned Int

c - 在递归函数中打印函数参数

c - 使用 "malloc"后的输出

c - 如何在按 CTRL + ALT + DEL 时停止此消息?