【发布时间】:2017-07-01 16:10:35
【问题描述】:
我有一个双轮列表数据结构,填充了保留:
struct reservation
{
unsigned int reservationID;
char *hotelName;
unsigned char noRoomsBooked;
char *clientName;
char *reservationPeriod;
float amount;
};
struct listNode
{
reservation inf;
listNode *next;
listNode *prev;
};
这是插入函数:
listNode *insertInList(listNode*head, listNode*tail, reservation r)
{
listNode *new= (nodLista*)malloc(sizeof(listNode));
new->inf.reservationId = r.reservationId;
new->inf.hotelName= (char*)malloc((strlen(r.hotelName) + 1) * sizeof(char));
strcpy(nou->inf.hotelName, r.hotelName);
new->inf.noRoomsBooked= r.noRoomsBooked;
new->inf.clientName= (char*)malloc((strlen(r.clientName) + 1) * sizeof(char));
strcpy(nou->inf.clientName, r.clientName);
new->inf.reservationPeriod= (char*)malloc((strlen(r.reservationPeriod) + 1) * sizeof(char));
strcpy(nou->inf.reservationPeriod, r.reservationPeriod);
new->inf.amount= r.amount;
if (head == NULL)
{
head = tail = new;
new->next = head;
new->prev = head;
}
else
{
listNode *temp = head;
while (temp->next != head)
{
temp = temp->next;
}
temp->next = new;
new->prev = temp;
new->next = head;
tail = new;
}
return head;
}
我想用我在 txt 文件中写的一些日期填充这个列表:
这是我的txt文件:
1,Hotel1,2,Client 1,10.05.2017-12.05.2017,200.5
2,Hotel2,1,Client 2,10.06.2017-17.06.2017,100.5
3,Hotel3,3,Client 3,03.03.2017-10.03.2017,800.5
4,Hotel4,2,Client 4,11.04.2017-15.04.2017,300.5
5,Hotel5,1,Client 5,10.05.2016-12.05.2016,150.5
从文件中读取的程序是这样的:
void main()
{
listNode *head= NULL, *tail= NULL;
reservation r;
FILE *f = fopen("Text.txt", "r");
while (!feof(f))
{
char buffer[200];
fgets(buffer, 199, f);
char *idRezervare = strtok(buffer, ",");
char *hotelName= strtok(NULL, ",");
char *noRoomsBooked= strtok(NULL, ",");
char *clientName= strtok(NULL, ",");
char *reservationPeriod= strtok(NULL, ",");
char *amount= strtok(NULL, ",");
r.reservationID= atoi(reservationID);
r.hotelName= (char*)malloc((strlen(hotelName) + 1) * sizeof(char));
strcpy(r.hotelName, hotelName);
r.noRoomsBooked= (int)noRoomsBooked;
r.clientName= (char*)malloc((strlen(clientName) + 1) * sizeof(char));
strcpy(r.clientName, clientName);
r.reservationPeriod= (char*)malloc((strlen(reservationPeriod) + 1) * sizeof(char));
strcpy(r.reservationPeriod, reservationPeriod);
r.amount= atof(amount);
head=insertInList(head, tail, r);
}
fclose(f);
printList(head);
当我在 No of Rooms Booked 字段中编译时,它会显示一个字符(每次编译时,它都是另一个字符,并且所有 5 行都相似)。 我猜错误来自这一行:
r.noRoomsBooked= (int)noRoomsBooked;
但我不知道如何解决它。
【问题讨论】:
-
您需要以类似于使用
atof的方式使用atoi。 (即)r.noRoomsBooked = atoi(noRoomsBooked); -
@CraigEstey 我试过了。它显示相同
-
我下载了您的源代码 [和数据文件] 并尝试编译它。如发布的那样,它有许多编译错误。由于这应该是一个足够小的程序,我会将您的整个/最新/最佳程序 [至少可以干净地构建] 重新发布为单个文件,以便其他人可以看到它并在他们愿意时在本地对其进行测试
-
C++?还是C?现在决定。
标签: c text char runtime-error