File I/O in C++
My question is how do you extract characters from a file putting them into it into some type of character array and then using an if statement to test what's in the character array?
For example, I want to read in all the characters of the 1st line of a text file and then test what the contents of the line say so I tried something like this:
ifstream file("file.txt")
char text[20];
file.getline(text, 20);
if(text == "DATA")
//do something
if(text== "EVENTS")
//do something else
But this of course fails since it looks at all elements of the array but even when I set the array to size 5 and then read in only 5 characters so all elements of the array are filled in it still fails. I guess you just can't test standard arrays in this manner? I also tried using char* text but the stream classes don't seem to like that and won't retrieve any data from the file at all. Anyone have any idea? Thanks in advance....
Edited by - Sheltem on 5/4/00 4:54:56 AM
The problem is that a line like
text = "DATA"
performs a pointer comparison, not a data comparison.
You could cast them into CStrings and use them for actual character-comparison.
#pragma DWIM // Do What I Mean!
~ Mad Keith ~
**I use Software Mode**
text = "DATA"
performs a pointer comparison, not a data comparison.
You could cast them into CStrings and use them for actual character-comparison.
#pragma DWIM // Do What I Mean!
~ Mad Keith ~
**I use Software Mode**
I got it! I was looking through VC 6.0 documenation on CString and it turns out when it compares strings it uses a standard C function called strcmp. So, I don't need to cast it to CString. I can directly compare the character array with a constant character array so I don't need to include some extra MFC overhead (I'm using Win32 and Direct X for the program). I did it like this if anyone cares:
if (strcmp(text, "DATA") == 0)
//do something
if (strcmp(text, "EVENTS") == 0)
//do something else
It only looks at the text I extracted from the file into the array because getline() inserts a null after the last character extracted and this strcmp function only looks at characters of the array until it hits a null. At least that's what I gather.
Thanks alot for the help.
Edited by - Sheltem on 5/4/00 6:17:00 AM
if (strcmp(text, "DATA") == 0)
//do something
if (strcmp(text, "EVENTS") == 0)
//do something else
It only looks at the text I extracted from the file into the array because getline() inserts a null after the last character extracted and this strcmp function only looks at characters of the array until it hits a null. At least that's what I gather.
Thanks alot for the help.
Edited by - Sheltem on 5/4/00 6:17:00 AM
No worries - should have remembered strcmp, but I''ve become a lazy MFC programmer
#pragma DWIM // Do What I Mean!
~ Mad Keith ~
**I use Software Mode**
#pragma DWIM // Do What I Mean!
~ Mad Keith ~
**I use Software Mode**
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement