【发布时间】:2017-04-07 21:42:07
【问题描述】:
这是我第一次使用文件输入和指针,如果我的代码看起来一团糟,我很抱歉。我正在查看其他 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。
编辑:哎呀删除了图像。
【问题讨论】:
-
对语句的malloc调用是否应该乘以1000而不是100?
-
不要发布文字图片,而是发布文字。
-
您的构建系统(或构建命令,您未与我们共享)放在一边的代码(其中的多个内容最终需要修复)已损坏。 Your code compiles(这绝不表示它是“正确的”)。
-
@JonnyHenly 哦,我现在看到了,你现在可以删除这条评论,我删除了我的。
-
它也在这里编译和链接。
标签: c file sorting compilation stdin