0

我有 txt 文件,其中有一行很多单词。我需要将它们全部写入一个数组。我查看了许多使用 fscanf 的示例,但是我无法理解它是如何工作的,因此我也无法在我的程序中使用它。所以问题是:我如何创建一个可以包含所有单词的数组,或者我应该只创建类似 a[999999] 的东西而不用担心它。如何将单词写入该数组,不包括“,”,“。”,“?” ETC?还有一个问题,我如何测量单词的大小(它有多少个字符)?

抱歉提出问题,感谢您的帮助。

4

1 回答 1

0

Untested sample. You should read up on each of these functions. To make sure you do, I'm deliberately not looking up the order of parameters as I normally should an am quite likely guessing wrong on some of the calls.

/* Untested Sample of "What it kinda should maybe look like" */
char buf[BUFSIZ];
fgets(stdin,buf); /*read a line*/
int i;
char *p;
for (p=buf,i=0; p+=strspn(p," .,"); i++) /*count delimiters*/; 
char **words;
words = malloc(i+1 * sizeof(char *));
for (i=0, words[0]=strdup(p=strtok(buf," .,"); words[++i]=strdup(p=strtok(NULL," .,"));) /**/;
words[++i]=NULL;

BUFSIZ should give you a pretty huge buffer (enough for any reasonable textfile). Scan the buffer and count delimiters to give a good guess at the max number of words we'll find. Allocate an array of char pointers. Fill the array with strdup copies of the return values from a sequence of calls to strtok. The first call to strtok passes the string as the first argument. Calls after that pass NULL as the first argument which means "keep using the same string". Also I'm not sure about that second loop termination. Treat this as pseudocode. :)

Edit: If you've got the word in a string, strlen will give you the length (not counting the terminating nul byte).

于 2012-12-15T15:04:42.033 回答