-1

我必须阅读带有学生名字和姓氏的文本文件。根据扭曲的程序要求,名字和姓氏是字符指针。使用 fgets 读取每一行。因此,我在数组结构中有变量 char *last_name, char *first_name。

例如:

比尔·克林顿

威廉,盖茨

我需要在运行时通过使用 strlen 和 strtok 指针来分配它们的大小......

问题是,如果我使用 strtok 和 strlen 来找出名称的长度,原来的 data_line 已经被分解了!有谁知道如何做到这一点?

4

1 回答 1

1

You've got all of the primary functions you'll need already named, so you're well on your way.

It makes sense that the names are char pointers. There is no string type in C, just arrays of characters. Also--and this is confusing--arrays and pointers are related in C. They're not the same, but they act the same in a number of cases. Consider that a function requiring a char pointer argument can accept either a char pointer or an array name (without the index). Also, notice that an array with an index is really just de-referencing a pointer to a certain address with the index indicating the offset.

So if you want a dynamically sized string, you're going to have to declare it as a char pointer and allocate memory for it dynamically (i.e., malloc). In your case, each first and last name varies in size--and you have one pointer for each--so you'll want one malloc for each of those. Using strlen() is still appropriate, as is using strtok() with multiple separator characters.

You may want to look at an example of strtok()--it can (and will) return each token one at a time. This link has a good example between the question and explanatory answers.

Edit: To be more specific, here is the core of what you're asking in code:

Getting a token:

token = strtok(data_line, sep);  // First token on data_line

Or:

token = strtok(NULL, sep); // Subsequent tokens on data_line

Then, example of allocating memory and storing the first name (last name is entirely analogous):

person[i].first_name = malloc(strlen(token) + 1);
strcpy(person[i].first_name, token);

The value of one added to strlen() result is to make space for the null terminator.

Edit 2: Rather than using malloc() and strcpy(), strdup() accomplishes both and would be preferable.

于 2012-12-02T02:15:29.780 回答