这是我第一次使用文件输入和指针,如果我的代码看起来一团糟,我很抱歉。我正在查看其他 Stack Overflow 解决方案作为引用。我的代码旨在查找文件中最长的单词,我可以假设输入文本中的单词不会超过 1000 个字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// main() must return an integer
int main(int argc, char** argv) {
FILE *file; //open an existing file
file = fopen(argv[1], "r"); //using argv as a pointer to an array of pointers to arrays of characters
char *sentence = (char *) malloc(100 * sizeof(char)); //memory allocation, unsure what to use for size*
//fgets - reads a line from the specified stream and stores it into the string pointed to
//max amount set to 1000
while (fgets(sentence, 1000, file) != NULL) {
char *word;
int maxlen = 0;
char *maxW;
//max size of 1000 characters
maxW = (char *) calloc(1000, sizeof(char));
word = (char *) calloc(1000, sizeof(char));
word = strtok(sentence, " "); //using strtok to break sentance to token
//checking size of word with maxlen
while (word != NULL) {
if (strlen(word) > maxlen) {
maxlen = strlen(word);
strcpy(maxW, word);
}
word = strtok(NULL, " ");
}
printf("%s\n", maxW); //printing the max sized word
maxlen = 0; //reset
return 0;
}
}
我一直只在 Windows 中使用命令行来使用 gcc 编译我的代码,我尝试使用 CLion,但我现在不知道如何使用 CLion。
编辑:哎呀删除了图像。
最佳答案
有几点观察:
- 句子的最大长度小于单词的最大长度。最好使用常量或宏来避免这样的拼写错误。
- 您正在使用
argv[1]
(命令行参数),但无法保证用户会发送文件名作为参数。最好使用适当的消息对此进行验证(argc 是参数计数)。 fopen
尝试打开文件,如果不能打开,返回 NULL,您的代码必须进行验证。- 代码为每一行分配了句子、单词和 maxW,但这是不正确的,因此将这些分配移至主代码的顶部。
word
只是一个指向sentence
的指针,所以它根本不需要分配内存。- 您的程序只读取第一行然后停止,那是因为它在
while
中有一个return 0;
。 - 始终
释放
您使用malloc
/calloc
分配的内存。
除了这些观察之外,您的代码几乎就在那里。
重组代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Using constants avoid typos
#define MAX_SIZE 1000
int main(int argc, char** argv) {
// Tokens not considered as part of a word
const char tokens[] = " \t\n\r,/:[]=().<>";
int maxlen = 0;
// calloc(a,b) == malloc(a*b)
char *sentence = (char *) malloc(MAX_SIZE * sizeof(char));
char *maxW = (char *) calloc(MAX_SIZE, sizeof(char));
char *word;
// try open and validate
FILE *file = fopen(argv[1], "rt");
if(file == NULL){
printf("file '%s' cannot be opened!\n", argv[1]);
return 1; // !=0 means error to OS
}
while (fgets(sentence, MAX_SIZE, file) != NULL) {
word = strtok(sentence, tokens);
while (word != NULL) {
if (strlen(word) > maxlen) {
maxlen = strlen(word);
strcpy(maxW, word);
}
word = strtok(NULL, tokens);
}
}
printf("Max word='%s' (len=%d)\n", maxW, maxlen);
// Don't forget free memory allocated with malloc/calloc
free(sentence);
free(maxW);
return 0;
}
并在同一个程序文件上执行:
$ gcc program.c
$ ./program program.c
Max word='considered' (len=10)
关于C:从文件输入排序,收到大量编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40771945/