0

多くの単語の行を含むtxtファイルがあります。それらすべてを配列に書き込む必要があります。fscanf が使用された多くの例を調べましたが、その仕組みを理解できなかったため、プログラムでも使用できませんでした。質問: すべての単語を含む可能性のある配列を作成するにはどうすればよいですか? または、この a[999999] のようなものを作成して、心配しないでください。「、」、「。」、「?」を除いて、その配列に単語を書き込むにはどうすればよいですか。等?もう 1 つの質問ですが、単語のサイズ (文字数) を測定するにはどうすればよいですか?

初心者の質問で申し訳ありません。助けてくれてありがとう。

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 に答える