سؤال

I'm new to C and I am trying to figure out how I can search for a specific string and the number that follows it in a file that has several numbers and words.

The input file that I'm using looks like this:

TREES 2
BENCHES 5
ROCKS 10
PLANTS 8

I know how to make a function read a string and I know how to compare two strings but I don't know how to put them both together or how to set the array up to read through the whole file.

I've been using strcmp, but I just don't know how to go about initializing the word I'm trying to look for.

هل كانت مفيدة؟

المحلول

You could do something like this:

#include <stdio.h>  // For file-handling methods
#include <string.h> // For strstr method

int main(void){
  FILE *fp;
  char *searchString="ROCKS";
  fp = fopen("myfile.txt", "r");
  char buf[100]; // Either char* buf or char buf[<your_buffer_size>]
  int myNumber = -1;
  while((fgets(buf, 100, fp)!=NULL)) {  //good to handle error as well
    if(strstr(buf, searchString)!=NULL) {
      sscanf(buf + strlen(searchString), "%d", &myNumber);
      break;
    }
  }
  printf("After the loop, myNumber is %d\n", myNumber);
  fclose(fp);
  return (0);
}

Disclaimer - untested. Should be close...

نصائح أخرى

Create an array that contains the words to search for. Create an outer loop that advances through your file stream of data one character offset at a time. Create a second inner loop that iterates over your array of terms to search for. The inner loop examines each term in the array against the data provided by the outer loop. Use strncmp to limit the length of each compare to the length of the word being searched for. Upon a match, check the following character in the source buffer to ensure it doesn't negate the match.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top