我以正确的方式获得了我的结构,而且看起来其中的大部分都在起作用。但是,我的字符串在我读取的文件中读取这个垃圾时遇到了一个小问题。我只想提取一个名称、日期和状态。它会在实际日期、名称或状态之前不断产生这种奇怪的形式 "]][]]]][[[[[["。如何让我的结构在没有收到垃圾反馈的情况下读取文件。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
#include <exception>
//functions called
void get_info(int id[], char name[][20], char state[][5], char dis_code[], float balance[], char due_date[][40]);
void print_list(int id[], char name[][20], char state[][5], char dis_code[], float balance[], char due_date[][40]);
//why is it void?
int main(void)
{
FILE *pFile;
int choice = 0;
char buf[40];
/*
int id[sizeof(buf)];
char name[sizeof(buf)][20];
char state[sizeof(buf)][5];
char dis_code[sizeof(buf)];
float balance[sizeof(buf)];
char due_date[sizeof(buf)][40];
*/
struct fileinfo
{
int id[40];
char name[40][20];
char state[40][5];
char dis_code[40];
float balance[40];
char due_date[40][40];
} info;
printf("WELCOME. \n");
while (choice != 5)
{
printf("press number for action\n");
printf("OPEN FILE - 1 \n");
printf("LIST THE TABLE - 2 \n");
printf("SEARCH THE TABLE -3 \n");
printf("ADD A NEW ROW - 4 \n");
printf("EXIT THE PROGRAM - 5 \n");
gets_s(buf);
choice = atoi(buf);
if (choice == 1)
{
pFile = fopen("ASSIGNV1.dat", "r");
if (pFile != NULL)
{
int i = 0;
for (i = 0; i < 8; i++)
{
//get id
fgets(buf, sizeof(buf), pFile);
info.id[i] = atoi(buf);
//get name
fgets(buf, sizeof(buf), pFile);
info.name[i][strlen(info.name[i]) - 1] = '\0';
//get state
fgets(buf, sizeof(buf), pFile);
info.state[i][strlen(info.state[i]) - 1] = '\0';
//get discount code
fgets(buf, sizeof(buf), pFile);
info.dis_code[i] = buf[0];
//get balance
fgets(buf, sizeof(buf), pFile);
info.balance[i] = atof(buf);
//get due date
fgets(buf, sizeof(buf), pFile);
info.due_date[i][strlen(info.due_date[i]) - 1] = '\0';
printf("ID \t\t %i \n", info.id[i]);
//problem with name
printf("NAME \t\t %s \n", info.name[i]);
//problem with state
printf("STATE \t\t %s \n", info.state[i]);
printf("DISCOUNT CODE \t %c \n", info.dis_code[i]);
printf("BALANCE \t %.2f \n", info.balance[i]);
//problem with due_date
printf("DUE DATE \t %s \n\n", info.due_date[i]);
}
}
printf("\n\nfile was opened and loaded\n\n");
}
}
printf("\n\n PROGRAM WILL END NOW");
system("pause");
}
我的文本文件是这样的:
125
LIPSO FACTO
SC
A
118.03
07/12/1998
193
GRADE BIT
OR
A
522.83
03/31/2003
237
MORE MATZOES
TN
846.29
01/11/2011
305
AIR BANGLEDESH
VT
A
3064
01/06/2005
485
FRED'S TATOOS
VT
C
2000.04
09/01/2007
520
WORLD WIDE WICKETS
WI
6280.43
04/29/1999
693
TAMMALIZATION
SC
B
3728
10/06/2009
746
REPLACEMENT PARTS
GA
C
5601.31
06/08/2003
最佳答案
可能您没有使用 strcpy()。您必须将 buf 复制到 info.name[i] 和 info.state[i]。
关于c - 使用结构读取文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22550593/