hi,
i created 2 text documents on my Desktop and wrote in them then i want to open these to files from c++.I wrote this program but every time i run it i get (-1#IND).
i have determined what the main problem is.When the files take1 and take2 reach the end it causes an error , i have tried many ways to put the cursor back at the top but it did not work.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char ID[9];
char ID2[9];
char name[20];
char lastname[20];
int assgrade=0;
int Mgrade=0;
int Fgrade=0;
float totalgrade=0;
ifstream take1("C:\\Users\\Georges\\Desktop\\student.txt",ios::in);
ifstream take2("C:\\Users\\Georges\\Desktop\\grades.txt",ios::in);
if(!take1 || !take2)
{
if(!take1)
cout<<"take1 could not be opened";
else
cout<<"take2 could not be opened";
return 1;
}
while(take1>>ID>>name>>lastname)
{
cout<<ID<<" "<<name<<" "<<lastname<<endl;
while(take2>>ID2>>assgrade>>Mgrade>>Fgrade)
{
cout<<ID2<<" "<<assgrade<<" "<<Mgrade<<" "<<Fgrade<<endl;
if(strcmp(ID,ID2))
{
totalgrade=((assgrade*25/100)+(Mgrade*35/100)+(Fgrade*40/100));
cout<<ID<<" "<<name<<" "<<lastname<<" "<<totalgrade<<endl;
continue;
}
}
take2.clear();
take2.close();
ifstream take2("C:\\Users\\Georges\\Desktop\\grades.txt",ios::ate);
}
int count=0;
float total=0;
while(take2>>ID2>>assgrade>>Mgrade>>Fgrade)
{
total+=Mgrade;
count++;
}
float average=0;
average=total/count;
cout<<average<<endl;
take1.close();
take2.close();
return 0;
}
and one more question:
how to open(read) an existing file without erasing its contents?
Hey I'm not sure what might be giving you that error, but I see one thing that worries me.
float totalgrade=0;
totalgrade is declared inside a loop.. not sure what happens if that statement is executed twice.. or if does that loop more than once in runtime, but you'd probly be best to declare totalgrade at the beginning of main() with yer other declarations.. then you can just say totalgrade = 0;
in that if block
btw LOL @ assgrade
nice identifier there bub
p.s. please use code tags when posting code. it's the button right above BOLD. makes it look so pretty..
and in this case might be useful to see the content of your text files too..
char ID[]="\0";
char ID2[]="\0";
char name[]="\0";
char lastname[]="\0";
//some code
while(take1>>ID>>name>>lastname) //read some stuff in to the arrays
//some other code
The ID and ID2 and name and lastname arrays are only 2 characters big each!
You are not going to fit much of a name or ID into an array of 2 chars ( you can only fit ONE char because you will need the second char to be the terminating \0 char)
yeah sorry i corrected this problem earlier but i didn't update my code here when i wrote it like this i was just trying different solution to try to fix my problem . now i have fixed part of the problem but the main problem is when the cursor reaches the end of the file this is giving the error.