首页 > 解决方案 > 如何将文件中的单词存储在单独的变量中?

问题描述

在这段代码中,我想选择一个单词并将其保存在一个单独的变量中。与文件中的所有单词相同。我已经给出了从文件中选择任何单词的选项(我评论过),当用户选择该单词时,它应该存储在一个变量中。这该怎么做?

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

int main(){
  FILE * fr = fopen("file.txt", "r");
  char string[100];

  if((fr = fopen("file.txt", "r")) == NULL){
    printf("Error! Opening file");
    exit(1);
  }
  while (fgets(string, 100, fr) != NULL){
    printf("%s", string);
    // printf("Write word to extract: ");
    // scanf("%s", ch);
    fclose(fr);
  }

标签: cfile

解决方案


当用户输入相同的单词时,我看不到它的用途。但是给你。

用于scanf()用户输入要查找的单词。用于fgets()从文件中获取行到字符串中。strtok()用于使用#define DELIMITERS.

从文件中扫描的单词存储在saved_word.

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

#define DELIMITERS " ,.-_!?"
#define STRING_LEN 100

int main(){
    FILE * fr = NULL;
    char string[STRING_LEN]; // Buffer for row in file
    char input[STRING_LEN]; // Buffer for input word
    char saved_word[STRING_LEN]; // To save the word in

    memset(string, 0, sizeof string);
    memset(input, 0, sizeof input);
    memset(saved_word, 0, sizeof saved_word);

    fr = fopen("file.txt", "r");

    if (fr == NULL)
    {
        printf("Error! Opening file");
        exit(1);
    }

    char* word = NULL;

    /**
     * User input of word to look for within file
     */
    printf("string: %s\n", string);
    printf("Enter what word you want to find: ");
    scanf("%s", input);
    printf("\n");

    printf("Start scanning file.\n");
    while (fgets(string, STRING_LEN-1, fr) != NULL)
    {
        printf("Scanned row.\n");

        /**
         * Use strtok() to scan through the row, stored in string
         * Manual says to only have string input parameter on first call
         */
        word = strtok(string, DELIMITERS);
        
        int diff;
        while (word != NULL)
        {
            diff = strcmp(input, word);
            if (diff == 0)
            {
                // Matching words! 
                printf("Found the word: %s\n", word);
                strcpy(saved_word, word);
            }
            word = strtok(NULL, DELIMITERS);
        }
        
    }

    fclose(fr);
  }

推荐阅读