开发者

help with C string i/o

Reads through a .txt file and puts all chars that pass isalpha() in a char array. for spaces it puts \0, so the characters in the array are separated by strings. This works.

I need help with the second part. I need to read a string that the user inputs (lets call it the target string), find all instances of the target string in the char array, and then for each instance: 1. print the 5 words before the target string 2. print the target string itself 3. and print the 5 words after the target string

I can't figure it out, i'm new to C in general, and I find this i/o really difficult after coming from Java. Any help would be appreciated, here's the code I have right now:

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

main(argc, argv)
int argc;
char *argv[];
{
  FILE *inFile;
  char ch, ch1;
  int i, j;
  int arrayPointer = 0;

  char wordArray [150000];
  for (i = 0; i < 150000; i++)
    wordArray [i] = ' ';

  /* Reading .txt, strip punctuation, c开发者_开发知识库onver to lowercase, add char to array */
  void extern exit(int);
  if(argc > 2) {
    fprintf(stderr, "Usage: fread <filename>\n");
    exit(-1);
  }

  inFile = fopen(argv[1], "r");
  ch = fgetc(inFile);

  while (ch != EOF) {
    if(isalpha(ch)) {
      wordArray [arrayPointer] = tolower(ch);
      arrayPointer++;
    }
    else if (isalpha(ch1)) {
      wordArray [arrayPointer] = '\0';
      arrayPointer++;
    }

    ch1 = ch;
    ch = fgetc(inFile);
  }

  fclose;

  /* Getting the target word from the user */
  char str [20];

  do {
    printf("Enter a word, or type \"zzz\" to quit: ");
    scanf ("%s", str);

    char* pch;
    pch = strstr(wordArray, str);

    printf("Found at %d\n", pch - wordArray + 1);
    pch = strstr(pch + 1, str);
  } while (pch != NULL);
}


There are a number of problems here, but the one that is probably tripping you up the most is the use of strstr as you've got it. Both parameters are strings; the first is the haystack, and the second is the needle. The definition of a C string is (basically) a sequence of characters terminated by '\0'. Take a look at how you've constructed your wordArray; it's effectively a series of strings one right after the other. So when you are using strstr the first time, you are only ever looking at the first string.

I realize this isn't the entire answer you are looking for, but hopefully it points you in the right direction. You may want to consider building up an array of char * that points into your wordArray at each word. Iterate over that new array checking for the string the user is looking for. If you find it, you now have an index you can work backwards and forwards from.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜