从各种各样的答案中可以看出,有很多很多方法可以解决这个问题。您提到您最终会将值存储在一些data structure 中。这提出了一个很好的考虑点。与其将每个值存储在单独的数组中,不如将值保存在一个集合中(例如 struct),这样您就无需跟踪多个容器的索引,这些容器包含您的数据的 pieces .
这并不是说使用多个鸽子洞是错误的,而是如果您在一开始就考虑一个有效的数据容器来解决问题,它可以简化所需的编码并使您的代码更加健壮。
由于您正在从stdin 读取数据,我将支持您使用面向行的输入(fgets 或@ 987654327@) 而不是试图将其归类为scanf 格式字符串(您也可以使用scanf 进行面向行的输入,但其他方法提供了一些优势)。
随着项目的推进,管理数据使用的内存将变得很重要。您可能希望根据需要分配内存,而不是静态分配X 的存储量。 (您仍然会分配一些初始存储块,但随着数据的增长,您可以根据需要轻松扩展。
牢记这些注意事项,以下是一个快速示例,说明如何在提供相当灵活的数据输入例程的同时合并它们,该例程将处理name number、first last number、first middle last, suffix number 等......合理地评论。如果您有任何问题,请发表评论。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXL 100
/* typedef to name and number struct */
typedef struct {
char *name;
char *num;
} nandn;
int main () {
char *line = NULL; /* buffer for getline (NULL forces allocation) */
size_t n = 0; /* maximum no. of char to read (0 - no limit) */
ssize_t nchr = 0; /* number of characters actually read */
int idx = 0; /* counter for array of struct index */
char *p = NULL; /* general char pointer to use for parsing */
nandn *nnlist = calloc (MAXL, sizeof (nnlist)); /* allocate MAXL structs */
printf ("\nEnter name and number to add to book [ctrl+d] when done.\n\n");
while (printf( " name number: ") &&
(nchr = getline (&line, &n, stdin)) != -1) {
if (line[nchr-1] == '\n') /* strip newline */
line[--nchr] = 0;
p = strrchr (line, ' '); /* find last space */
if (!p) break; /* exit read - invalid input */
(nnlist + idx)->num = strdup (++p); /* read number */
*(--p) = 0; /* return to space and set null */
(nnlist + idx)->name = strdup (line); /* read name (all else in line) */
idx++; /* NOTE: if idx = MAXL - 1
* reallocate nnlist */
}
if (line) free (line); /* free memory allocated by getline */
printf ("\n\nThe information collected was:\n\n");
int i = 0; /* print all values in nnlist array */
while ((nnlist + i)->name) {
printf (" nnlist[%d] %-24s %s\n", i, (nnlist + i)->name, (nnlist + i)->num);
i++;
}
printf ("\n");
i = 0; /* free all memory for nnlist */
while ((nnlist + i)->name) {
free ((nnlist + i)->name);
free ((nnlist + i)->num);
i++;
}
free (nnlist);
return 0;
}
输出:
$./bin/namnum
Enter name and number to add to book [ctrl+d] when done.
name number: Jane Doe, Md. 8005551212
name number: Mike M. Mills, Jr. 2145551212
name number: Alphred Funk, III 2025551212
name number:
The information collected was:
nnlist[0] Jane Doe, Md. 8005551212
nnlist[1] Mike M. Mills, Jr. 2145551212
nnlist[2] Alphred Funk, III 2025551212