Hi everyone:
Any suggestions on the best way to read:
student name
student number
90 100 23 65 (<-- four marks there)
from a text file and store them in a struct?
the 4 marks are separated by spaces..
Thanks.
Hi everyone:
Any suggestions on the best way to read:
student name
student number
90 100 23 65 (<-- four marks there)
from a text file and store them in a struct?
the 4 marks are separated by spaces..
Thanks.
I did something like this as an exercise once.
Although it was onlt 3 marks not 4.
Code:#include <string> #include <fstream> #include <iostream> using namespace std; #define FILE_NAME "File.txt" struct STUDENT_INFO { string Name; string Number; int Mark1; int Mark2; int Mark3; }; int main(void) { STUDENT_INFO stu; string LastName; ifstream in; in.open(FILE_NAME); in>>stu.Name; in>>LastName; stu.Name = stu.Name + ' ' + LastName; in>>stu.Number; in>>stu.Mark1; in>>stu.Mark2; in>>stu.Mark3; cout<<stu.Name <<endl; cout<<stu.Number <<endl; cout<<stu.Mark1 <<endl; cout<<stu.Mark2 <<endl; cout<<stu.Mark3 <<endl; return 0; }
does the >> operator read in things until it encounters a space?
so if it's like:
student name
student number
mark1 mark2 mark3 mark4
in the file, it'll read student name with the first >>, student number with the second >>, mark 1 with the third, mark2 with the fourth, and so on?
Thanks
sorry that was actually me, i forgot to sign in first..
ok i guess it'll help if i put everything in one post:
here's what's in the file:
sarah
23456
12 100 98 46
and here's the code:
will that code store the file contents into stu properly?PHP Code:
#include <string.h>
#include <fstream.h>
#include <iostream.h>
struct studentinfo
{
char name[20];
char number[20];
int marks[4];
};
void main()
{
studentinfo stu;
ifstream sourcefile;
int c;
sourcefile.open("filename.txt");
sourcefile>>stu.name;
sourcefile>>stu.number;
for (c=0; c<4; c++)
sourcefile>>stu.marks[c];
return;
}
Thanks a lot for your help.
If student name and number contain no whitespace (space, tab, newline, etc) it should work fine. With a liitle added work to create an array/container of studentinfo, you can wrap the code in a while loop looking for end of file marker to read multiple instances of a the struct.
As an alternative, iff the information on students is written to file using the write() method, such that it is in binary form, then you can use the read() method to read informtion into a given struct with one fell swoop.
okay
Thank you!
You can take out the "#include <string.h>" tho.