How do I create an infile with ifstream?

// open the infile
ifstream inFile;
inFile.open ("in6s17.txt");


//display error message
if (!inFile) {
cout << "Error opening infile." << endl;

}

else
{
for (int count=0; count<MONTHS; count++)
rainfallAmount[count];

}

//close the infile
inFile.close();

I'm completely aware it's all wring, but I don't know how to use the ifstream.

Also how do I view it with xcode?

Best program I ever wrote! I use it all the time.
With a few changes you can make it do anything with a line of data.
Instead of hard coding the file name you enter it on the command line.
much better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#Counts number of lines and displays count and lines on screen.
#include <fstream>
#include <iostream>
using namespace std;

int linecount=1;
string line;

int main (int argc, char *argv[])
{
    if (argc!=2)
    {
        cout << "Incorrect arguments\n";
    }
	else
	{
	ifstream inputfile (argv[1]);
    if (inputfile.is_open())
	{
	while ( inputfile.good())
		{
		getline (inputfile,line);
		if (!line.empty())
		{
					cout << linecount << " " << line << endl;
					linecount++;
		}
		}

	inputfile.close();
    }
	else
		{
		        cout << "File not open" << endl;;
		}
	}
return 0;
}
Ooh that looks great, except for I'm looking for something more simple without the argc,
*argv, and linecount. Also hard coding the file name, the only way I learned to do it :L I still have to use the if (inputfile.is_open()) though xD
I still have to use the if (inputfile.is_open()) though xD

No you don't. Your if (!inFile) is fine, just a shorter form.
To read sth. from the ifstream you need to use the operator >>, for example
1
2
3
4
5
6
7
8
9
10
ifstream inFile("filename.txt");
if (!inFile)
{
   perror("File error:");
}
else
{
   int number;
   inFile >> number; // reads an int into number
}
Oh okay. Thanks!
Topic archived. No new replies allowed.