【发布时间】:2013-06-30 04:23:39
【问题描述】:
我创建了一个 C 程序,我应该在其中读取一个文本文件并通过 int 和 string 指针将其分配给一个结构。
这是我的程序的代码 sn-p:
i = 0;
while(!feof(phoneBook)) {
fscanf(phoneBook, "%d|%s\n", &num, fname);
info[i].phone_num = num;
printf("%d\n", info[i].phone_num);
info[i].first_name = fname;
printf("%s\n", info[i].first_name);
i++;
ctr++;
printf("\nfirst:%s", info[0].first_name);
printf("\nsecond:%s", info[1].first_name);
printf("\nthird:%s\n\n", info[2].first_name);
}
在第一次迭代中,它将第一行分配给 info 的 0 索引。 对于第二次迭代,它将第二行分配给索引 1 并替换索引 0。
文本文件仅包含以下几行(用于测试目的): 第一的 第二 第三个
这是输出:
//first iteration
first:first
second: <null>
third: <null>
//second
first:second
second: second
third: <null>
//third
first:third
second: third
third: third
顺便说一句,我将我的结构声明为:
typedef struct{
int id;
char *first_name;
char *last_name;
int phone_num;
} phone_det;
其中 phoneBook 在数据类型 phone_det 下声明。
我们将不胜感激任何形式的帮助!我刚开始使用 C,但我仍然对指针感到有些困惑。 :(
【问题讨论】:
-
你的信息结构是什么样的?它是如何声明的?
-
不要这样使用
feof();它给了你错误的答案。更具体地说,您必须检查来自fscanf()的值,因为它会在feof()之前告诉您有关EOF 的信息。 -
更新你的问题;不要将结构添加为注释。
-
谢谢大家!终于实现了整个指针字符串数组的事情。现在没事了。非常感谢!!!!!! :)