简体   繁体   English

从文本文件中读取,并使用每一行进行比较,看看它们是否是字谜

[英]Read from a text file and use each line to compare if they are anagrams

I must modify my program to accept input from a file called anagrams.txt.This file should have two strings per line, separated by the # character. 我必须修改程序以接受来自名为anagrams.txt的文件的输入。此文件每行应有两个字符串,以#字符分隔。 My program should read each pair of strings and report back if each pair of strings is an anagram. 我的程序应读取每对字符串,如果每对字符串都是一个字谜,则应进行报告。 For example consider the following content of anagrams.txt: 例如,考虑以下anagrams.txt内容:

hello#elloh 你好#elloh
man#nam 男人#南
Astro#Oastrrasd 天文#Oastrrasd

Your program should print out the following: 您的程序应打印出以下内容:

hello#elloh - Anagrams! hello#elloh-字谜!

man#nam - Anagrams! man#nam-字谜!

Astro#Oastrrasd- Not anagrams! Astro#Oastrrasd-不是字谜!

I should compile in g++ 我应该用g ++编译

Here is the code to read from text: 这是从文本读取的代码:

int main()
{
    char input[30];




      if(access( "anagrams.txt", F_OK ) != -1)           {

            FILE *ptr_file;
        char buf[1000];

        ptr_file =fopen("anagrams.txt","r");     if (!ptr_file)
            return 1;

        while (fgets(buf,1000, ptr_file)!=NULL)
            printf("%s",buf);

    fclose(ptr_file);
        printf("\n");
      }

      else{ //if file does not exist
        printf("\nFile not found!\n");
      }


        return 0;
}

Code to find if the text are anagrams: 查找文本是否为字谜的代码:

 #include <stdio.h>

int find_anagram(char [], char []);

int main()
{
    char array1[100], array2[100];
    int flag;

    printf("Enter the string\n");
    gets(array1);
    printf("Enter another string\n");
    gets(array2);
    flag = find_anagram(array1, array2);
    if (flag == 1)
        printf(" %s and %s are anagrams.\n", array1, array2);
    else
        printf("%s and %s are not anagrams.\n", array1, array2);
    return 0;
}

int find_anagram(char array1[], char array2[])
{
    int num1[26] = {0}, num2[26] = {0}, i = 0;

    while (array1[i] != '\0')
    {
        num1[array1[i] - 'a']++;
        i++;
    }
    i = 0;
    while (array2[i] != '\0')
    {
        num2[array2[i] -'a']++;
        i++;
    }
    for (i = 0; i < 26; i++)
    {
        if (num1[i] != num2[i])
            return 0;
    }
    return 1;
}

Since this looks like a University question, I won't provide a full solution, only a hint. 由于这似乎是一个大学问题,因此我将不提供完整的解决方案,仅提供提示。

All you have to do is replace the stdin input part of the anagram-finding file with the code you wrote to read from a file: it's as simple as changing 您所要做的就是用您编写的从文件读取的代码替换anagram-finding文件的stdin输入部分:就像更改一样简单

printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);

to // before program: #define SIZE 1000 到//在程序之前:#define SIZE 1000

// inside main

if (access("anagrams.txt", F_OK) == -1){
    printf("\nFile not found!\n");
    return 1; // Abort the program early if we can't find the file
}
FILE *ptr_file;
char buf[1000];

ptr_file = fopen("anagrams.txt","r");
if (!ptr_file)
    return 1;

char array1[SIZE], array2[SIZE];

while (fgets(buf, 1000, ptr_file)!=NULL){
    // do all your anagram stuff here!
    // there is currently one line of the input file stored in buf

    // Hint: You need to split buf into array_1 and array_2 using '#' to separate it.

}


fclose(ptr_file);
printf("\n");

Additional comments: 附加评论:

  1. Don't ever ever ever use gets . 永远不要使用gets gets doesn't check that the string it writes to can hold the data, which will cause your program to crash if it gets input bigger than the array size. gets不会检查它写入的字符串是否可以保存数据,如果输入的数据量大于数组大小,这将导致程序崩溃。 Use fgets(buf, BUF_SIZE, stdin) instead. 请改用fgets(buf, BUF_SIZE, stdin)
  2. Beautiful code is good code. 漂亮的代码就是好的代码。 People are more likely to help if they can read your code easily. 如果人们可以轻松阅读您的代码,则他们更有可能提供帮助。 (fix your brackets) (固定括号)
  3. Just for interest, a more efficient algorithm for checking anagrams is to use qsort to sort both arrays, then a simple string matcher to compare them. 只是出于兴趣,一种用于检查字谜的更有效算法是使用qsort对两个数组进行排序,然后使用简单的字符串匹配器对其进行比较。 This will have cost O(mnlog(m+n)) , as opposed to O(m^2 n^2) , awith the current algorithm 与当前算法相比,这将具有成本O(mnlog(m+n)) ,而不是O(m^2 n^2)

You need to split every line you read by fgets (as you did) in to two strings, and pass them to your find_anagram function. 您需要将fgets读取的每一行(与您所做的一样)分成两个字符串,并将它们传递给find_anagram函数。 You can do that using strtok : 您可以使用strtok做到这一点:

int main()
{
  int flag;
  char buf[1000];
  FILE *ptr_file;

  //Check file existence

  //Open the file for reading

  while (fgets (buf, 1000, ptr_file) != NULL)
    {
      char *array1 = strtok(buf, "#");
      char *array2 = strtok(NULL, "\n");

      flag = find_anagram (array1, array2);

      //Check flag value to print your message
    }

  return 0;
}

//put your find_anagram function

Don't forget to #include <string.h> to use strtok() . 不要忘了#include <string.h>使用strtok()

You can try something like this: 您可以尝试如下操作:

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

#define MAXLINE 1000
#define MAXLETTER 256

int is_anagram(char *word1, char *word2);
void check_lines(FILE *filename);
int cmpfunc(const void *a, const void *b);
void convert_to_lowercase(char *word);

int
main(int argc, char const *argv[]) {
    FILE *filename;

    if ((filename = fopen("anagram.txt", "r")) == NULL) {
        fprintf(stderr, "Error opening file\n");
        exit(EXIT_FAILURE);
    }

    check_lines(filename);

    fclose(filename);

    return 0;
}

void
check_lines(FILE *filename) {
    char line[MAXLINE];
    char *word1, *word2, *copy1, *copy2;

    while (fgets(line, MAXLINE, filename) != NULL) {
        word1 = strtok(line, "#");
        word2 = strtok(NULL, "\n");

        copy1 = strdup(word1);
        copy2 = strdup(word2);

        convert_to_lowercase(copy1);
        convert_to_lowercase(copy2);

        if (is_anagram(copy1, copy2)) {
            printf("%s#%s - Anagrams!\n", word1, word2);
        } else {
            printf("%s#%s - Not Anagrams!\n", word1, word2);
        }
    }
}

void
convert_to_lowercase(char *word) {
    int i;

    for (i = 0; word[i] != '\0'; i++) {
        word[i] = tolower(word[i]);
    }
}

int
is_anagram(char *word1, char *word2) {

    qsort(word1, strlen(word1), sizeof(*word1), cmpfunc);
    qsort(word2, strlen(word2), sizeof(*word2), cmpfunc);

    if (strcmp(word1, word2) == 0) {
        return 1;
    } 
    return 0;
}

int
cmpfunc(const void *a, const void *b) {
    if ((*(char*)a) < (*(char*)b)) {
        return -1;
    }

    if ((*(char*)a) > (*(char*)b)) {
        return +1;
    }

    return 0;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用fgets从文件中读取行,并将每行与c中的strncmp进行比较 - read lines from file with fgets and compare each line with strncmp in c 逐行读取文本文件并检索C中每一行的内容 - Read a text file line by line and retrieve the content of each line in C 我想从标准输入中读取文件,并将每一行读入字符串,仅使用getchar - I want to read a file from stdin and read each line into a string and only use getchar 逐行读取文本文件并将每行保存在缓冲区中,而不管每行的数据类型和长度 - Read a text file line by line and save each line in the buffer irrespective of data type and length of each line 从文本文件的一行中获取每个单词 - Get each word from a line in a text file 读取文本文件,将每一行分成单独的数组,然后在C中排序 - Read text file, break each line into separate arrays and sort in C 从文本文件中读取一行并删除它 - Read a line from text file and delete it 从文件中读取每一行,然后在C中将该行拆分为一个字符串和一个数组 - Read each line from a file and split the line into a string and an array in C 如何读取c中的文本文件,然后将每一行拆分为标记? - how to read a text file in c and then split each line into tokens? 从C中的数据文件读取文本行 - read a text line from a data file in C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM