Longest and Shortest word in a file C programming -
hello , evening,
so i'm writing program in c, accept file.txt input , read text. program should read text file, find longest , shortest word within file, , print them out when reaches end.
i'm close i'm getting seg fault and, not not know why, i'm @ loss how fix it.
here's code:
#include <stdio.h> #include <string.h> file *fp; char str[60]; char *largest; char *smallest; char *word; int i, j; int main (int argc, char **argv) { // check there 2 arguments if (argc == 2) { fp = fopen(argv[1], "r"); } // if not throw error else { perror("argument error."); return (-1); } // check if file exists if (fp == null) { perror("error opening file."); return (-1); } // set largest first string , smallest second largest = strcpy(largest, strtok(str, " ")); smallest = strcpy(smallest, strtok(null, " ")); word = strcpy(word, strtok(str, " ")); // while lines of file while (fgets (str, 60, fp) != null) { // while token string isn't empty while (word != null) { if (strlen(largest) > strlen(word)) { strcpy(word, largest); } if (strlen(smallest) < strlen(word)) { strcpy(word, smallest); } } } printf("the largest word in file is: %s", largest); printf("the smallest word in file is: %s", smallest); fclose(fp); return 0; }
i'm pretty sure it's second while loop...i don't want use anyway, i've been hacking @ long it's logic can think of.
any appreciated. homework, though small part of it, , i'm not asking helping solving entire problem.
also, there makefile involved...i don't think it's important post feel free ask me , i'll update.
as built can confirm file able read , can print, put, , kinds of cool things. broke when tried implement logic longest/shortest word.
thanks!
there problems logic. try below code
few assumptions made are,
maximum word length 20 characters. can change max_word_length macro. words in file space separated max line length 60 characters
#include <stdio.h> #include <string.h> #include <stdlib.h> #define max_word_length 20 int main (int argc, char **argv) { file *fp; char str[60]; char *largest = (char*) malloc (max_word_length); char *smallest = (char*) malloc (max_word_length); int smallest_len = max_word_length, largest_len = 0; if (argc == 2) { fp = fopen(argv[1], "r"); } else { printf("argument error."); return (-1); } if (fp == null) { printf("error opening file."); return (-1); } while (fgets (str, 60, fp) != null) { char *temp = strtok(str, " "); while (temp != null) { if (strlen(temp) > largest_len) { strcpy(largest, temp); largest_len = strlen(largest); } if (strlen(temp) < smallest_len) { strcpy(smallest, temp); smallest_len = strlen(smallest); } temp = strtok(null, " "); } } printf("the largest word in file is: %s\n", largest); printf("the smallest word in file is: %s\n", smallest); fclose(fp); return 0; }
Comments
Post a Comment