# Thread: C++ input

1. ## C++ input

Code:
  #include <iostream>
#include <fstream>
#include <math.h>

using namespace std;
int main()
{

char str[2000];
fstream file_op("C:\\IndusCommodities\\PriceFiles\\AllMarkets-1.txt",ios::in);
if (!file_op.is_open())
{

cerr << "Unable to open the file" << endl;
return -1;

}
while(!file_op.getline(str, sizeof(str)))
{
cout <<str;
}

file_op.close();

cout <<endl;

return 0;

}
I am trying to read in a text file and print out the result. The program compiles and executes fine, but nothing comes on the screen.

2. Originally Posted by heathrowjohnny
I am trying to read in a text file and print out the result. The program compiles and executes fine, but nothing comes on the screen.
The main problem is that basic_ios::operator! will return true when the stream is bad, and false otherwise. So your while condition is backwards.

Other things:

Don't use a statically-allocated char array for things like this. Although the second parameter of getline will prevent a buffer overflow, it would be much better to use C++ style strings here (you will need to use the global getline function, defined in <string>). Also, keep in mind it is usually poor style to dump the entire std namespace like that, but for a tiny program like this there isn't a problem. And it is not necessary to call file_op.close at the end, because the fstream destructor will do it automatically.

I would rewrite it as:

Code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
fstream file_op("C:\\IndusCommodities\\PriceFiles\\AllMarkets-1.txt", ios::in);

if(!file_op.is_open())
{
cerr << "Unable to open the file" << endl;
return -1;
}

string line;
while(file_op && !file_op.eof())
{
getline(file_op, line);
cout << line << '\n';
}

return 0;
}
<math.h> isn't needed here, but if you are going to use it, I suggest using <cmath> instead, since everything will be placed in the std namespace that way.

3. thanks. I was using <math.h> because I will need it later. Yeah I am just learning C++ but know some Java.