![]() |
| | #1 |
| Registered User Join Date: Oct 2009
Posts: 10
| I have a problem to read data from a Database.txt file. The file contains the questions and answers for the quiz, and I have to read it from a file and put it to a structure so I can use it in program. I have done this with a binary file, but unfortunately I must use txt. this is an example of questions in txt file. Of course, there are more, but I'll put just 2 of them here. 1. Koji programski jezik nije objektno orijentisan? //this is a question 1)Java 2)C++ 3)Visual Basic 4)C //these 4 are the answers 4 // and this is the number of the correct answer 2. Sta je od navedenog model boja u racunaru? 1)PDF 2)DBMS 3)RGB 4)USD 3 now I will give you the structure I have made to put the data from the file in: Code: struct milioner
{
char question[MAX], answers[4][MAX];
int correct;
};
// and I have tried to read the file and put it in a structure with this code, but it doesn't work
FILE *ptr;
struct milioner q[BROJ];
int i,j;
ptr=fopen("Database.txt","r");
if(ptr==NULL)
printf("Error reading file.");
if(!feof(ptr))
{
for(i=0;i<BROJ;i++)
{
fgets(q[i].question,MAX+1,ptr);
for(j=0;j<4;j++)
fgets(q[i].answers[j],MAX+1,pok_dat);
fscanf(ptr,"%d",q[i].correct);
}
}
|
| Makaila is offline | |
| | #2 |
| Registered User Join Date: Jun 2008
Posts: 1,526
| Code: fgets(q[i].question,MAX+1,ptr); If you have MAX+1, it will read MAX characters and then add the '\0' character on the end. Since you have MAX characters in your buffer the program will do something bad. The other thing is that I am not sure fscanf will work like this. In general be careful when mixing different input functions. I believe fscanf() will leave the newline character in the buffer, so the next fgets() function will read just that and exit. About feof() look at this and the FAQ. Combining that with using fscanf() and fgets() unexpected things might happen. My advice? Just use fgets() and atoi() And what is pok_dat in your code??? |
| C_ntua is offline | |
| | #3 |
| Registered User Join Date: Oct 2009
Posts: 10
| oh, pok_dat is the name for ptr in my program, I forgot to rename it to ptr for this thread. And, thanks a lot for the advice... It is ok now. |
| Makaila is offline | |
![]() |
| Tags |
| answers, file, questions, quiz |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| File transfer- the file sometimes not full transferred | shu_fei86 | C# Programming | 13 | 03-13-2009 12:44 PM |
| Post... | maxorator | C++ Programming | 12 | 10-11-2005 08:39 AM |
| Problem reading data from file and record it for use in program | timmer | C Programming | 20 | 06-12-2005 11:53 PM |
| airport Log program using 3D linked List : problem reading from file | gemini_shooter | C Programming | 3 | 03-04-2005 02:46 PM |
| Problem reading file | winsonlee | C Programming | 2 | 04-23-2004 06:52 AM |