【发布时间】:2017-09-03 00:31:16
【问题描述】:
我正在尝试从文本文件创建一个单词数组。我能够让它正确打印出值,但我需要一个可以实际使用的数组。在我拥有这个数组之后,我必须对我存储的单词做各种事情,比如计算每个单词的长度。现在我只需要帮助制作一个我可以实际使用的数组。
代码如下:
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main ( int argc, char* argv[]){
// First Read in First novel File
FILE *fp;
char *ProgFile;
// Variables for Parsing
int i = 0;
int j=0;
char *cp;
char *bp;
char line[255];
char *array[5000];
int x;
int wordCount=0;
int wordCountPerNovel;
// Adjusting the file name to include txt and corresponding number
strcat(argv[1],"_1.txt");
ProgFile = argv[1];
// Open Each File
fp=fopen(ProgFile,"r");
if( fp==NULL )printf("error");
else printf("bin file loaded: '%s'",ProgFile);
// Now begin analysing
// Part 1
// Parse Entire Document into Array of Strings
while (fgets(line, sizeof(line), fp) != NULL) {
bp = line;
while (1) {
cp = strtok(bp, ",.!?<97> \n");
bp = NULL;
if (cp == NULL)break;
array[i++] = cp;
printf("Check print - word %i:%s:\n",i-1, cp);
}
}
// At this point i is the last word that was iterated, -1 since it breaks out after being added
// This gets total words of all novels
wordCount=wordCount+(i-1);
printf("\nTotal words %i\n",wordCount);
// Find Total number of letters
//for (i=1;i<15;i++){
// printf("My value: %s \n",finalArrayWord[i]);
//
//}
【问题讨论】:
-
你实际上并没有问问题。
-
什么是我可以实际使用的数组?
-
1)
strcat(argv[1],"_1.txt");不能这样。 -
你有一个问题,当你分配 array[i++] = cp 时,你正在使用相同的内存区域。在下一个循环中,您将在执行 fget(line) 时覆盖,因为 strtok 将返回指向 line 的指针。当您第二次调用 strtok 时,您还有另一个错误,请查看 strtok 手册页。
-
和@BLUEPIXY 是对的,你可以在 argv 之后写,内存不是你的,你必须做类似 snprintf(myNewString,maxlenofMyNewString,"%s_1.txt",argv[1]) ;我认为你必须学习一些关于在 C 中使用内存和指针的知识。
标签: c arrays file input document