kmabg9x bắt đầu chủ đề từ 5 năm trước

@Tu Nguyen ·


Bài hiện tại chỉ trả về kết quả vị trí đầu tiên, mình muốn tìm vị trí còn lại

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
#define MAX_SIZE 1000
int main()
{
    /* File pointer to hold reference of input file */
    FILE * fPtr;
    FILE * fTemp;
    char path[100];
    char buffer[BUFFER_SIZE];
    char oldWord[100], newWord[100];
    int line, col,i;

    printf("Enter file name: ");
    scanf("%s", path);
    fPtr  = fopen(path, "r");
    fTemp = fopen("replace.tmp", "w");

if (fPtr == NULL || fTemp == NULL)
    {
        /* Unable to open file hence exit */
        printf("\nUnable to open.\n");
        printf("Please check your file.\n");
        exit(EXIT_SUCCESS);
    }
    else
    {
        printf("Input a word: ");
        scanf("%s", newWord);

        indexOf(fPtr, newWord, &line, &col);
        if (line!= -1)

        printf("line: %d, col: %d\n", line+1, col + 1);
      fclose(fPtr);
}
}
int indexOf(FILE *fptr, const char *word, int *line, int *col)
{
    char str[BUFFER_SIZE];
    char *pos;
    *line = -1;
    *col  = -1;
    while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
    {
        *line += 1;

        // Find first occurrence of word in str
        pos = strstr(str, word);

        if (pos != NULL)
        {
            // First index of word in str is
            // Memory address of pos - memory
            // address of str.

            *col = (pos - str);
             col++;

            break;
        }
    }
    // If word is not found then set line to -1
    if (*col == -1)
        *line = -1;

    return *col;

}

Viết câu trả lời

Drop Images

1 Bình luận

phaptl avatar
  • Đầu tiên ở class indexOf bạn khai báo một mảng listIndex.
  • Sau đó trong hàm kiểm tra điều kiện trả về vị trí if (pos != NULL) chỗ break bạn xóa đi thay vào chỗ đó là thêm vào mảng listIndex vị trí thỏa mãn đó. Và cuối cùng ở dòng return *col; thay bằng return listIndex;
  • Mấu chốt ở đây là lệnh break, lệnh này ngắt mọi công việc trong vòng lặp while, khi đặt trong hàm điều kiện kia ý nghĩa của nó là "nếu tìm được rồi thì dừng lại, không lặp lại việc tìm kiếm nữa"