简体   繁体   中英

How to separate words from numbers in file in c

I need to find the degree of inversion for a set of numbers in a file.

I read input from a .txt file in the form:

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

I do not know how to separate the input (the set and its numbers). I thought of putting them in a struct but so far it's not working. The degree of inversion = number of numbers that are smaller than their index value. For example, in SET 2, the degree of inversion is 0.

You need to post code on where you are stuck; that is the best way to get help. Anyway, here is some rough code to help you identify where your issues may be. I have kept it simple to allow you to follow through with how vanilla C does 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM