简体   繁体   中英

Parse 2d character array

I have a text file as follows:

Rank Title Weekend Box Office

1 American Sniper $31,850,000

2 Paddington $8,505,000

I put each line into a 2d character array. I want to separate each line and put all the ranks in one array, all the titles in another array and all the weekend box office's in another.

How do you go about parsing the char data[5][200] such that I can get the string value only. I was thinking along the lines of the %s specifier, but I don't know which method to use it with (new to c).

//-------Text File Implementation-----------
    FILE *fp;
    char data[5][200];

    /* opening file for reading */
        fp = fopen("movie.txt", "r");
        if(fp == NULL) {
            perror("Error opening file");
            return(-1);
        }


        int i = 0;
        while(fgets (data[i], 200, fp)!=NULL)
        {
        /* writing content to stdout */
            puts(data[i]);
            i+=1;

        }

        fclose(fp);

You can do with the sscanf() link.

After getting the input from the file,

  int val; 
  char name[255],char value[100];
  sscanf(data[i],"%d %[^$] %s",val,name,value);

You can parse using strtok()

Here you can read each line in, then tokenize. This is an example that you can try out.

#include <string.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
  char text[255] = "1 American Sniper $31,850,000";

  const char *rank = strtok(text, " ");
  const char *name = strtok(NULL, "$");
  const char *amount = strtok(NULL, "\n");

  printf("%s|%s|%s\n", rank, name, amount);
}

This outputs "1|American Sniper |31,850,000". You'll lose the $ sign, but you can add it back easily.

For the rest of your code structure, I'd recommend creating a single line buffer to read each line in and process it separately, then just keep the tokens after that.

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