-
Reading text files
Hi everyone! I'm just getting into C++ but I have a some experience in programming (if JavaScript counts...)
anyways I was wondering how you would check to see if there is text in a file (as opposed to none at all). For example in JavaScript I would do something like:
Code:
if (text_in_file!="") { ... }
but it doesnt seem to work in C++...heres what i was doing in C++ (trimmed down to the problem):
Code:
char *str = new char[50];
ifstream read_file("example.txt");
read_file>>str;
read_file.close();
if (str!="") //<--heres where im stuck
{
//code goes here
}
else
{
//code goes here
}
-
Heres a better way
[code]
#include <iostream>
#include <fstream>
int main()
{
char *Buffer;
ifstream fin;
Buffer= new char[80];
fin.open("Example.txt");
fin >> Buffer;
fin.close();
if( !Buffer )
{
cout << "Theres nothing in the text file!!"; << endl;
}
delete [] Buffer;
cin.get();
return 0;
}
-
Hm that doesn't seem to be working...are you sure the ( !Buffer ) is the right way to check if the file is empty?
-
or
Code:
#include <iostream>
#include <fstream>
int main()
{
char Buffer[80]
fstream file("Example.txt", ios::in);
file >> Buffer;
if( !Buffer ) // Checks the contents of the buffer. If its empty then it proceeds the following code.
{
cout << "No text detected!!" << endl;
}
else
{
cout << Buffer << endl;
}
file.close();
cin.get();
return 0;
}
-
Newbie helping a newbie!! There is an easier way!!
-
Heh still no luck. What's the cin.get(); for?
-
my bad, replace if( !Buffer ) with if( (strlen(Buffer))==0)
-
ah ok thank you...im guessing the cin.get is to keep it from closing instead of using system("PAUSE")?
-
Yes, because system("PAUSE") is OS dependent.