Trouble with files!

Nov 13, 2015 at 2:06pm
My question is how would I go about opening an existing file, calculating the numbers in it and determining how many values there are in it

lets say this file reads:
100
200
300

This is what i have thus far:


1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <fstream>

int main(){
	ofstream outfile;
	outfile.open("C:\Users\Tyler\Desktop\CS Source\Chapter 05\numbers.txt");


	return 0;
}
Nov 13, 2015 at 2:30pm
If the file already exists, then you need to use an input file stream. Also, use the forward slash '/' as the separator in the pathname of the file.
1
2
    ifstream infile;
    infile.open("C:/Users/Tyler/Desktop/CS Source/Chapter 05/numbers.txt");


Once you've done that, the stream infile can be used for input using similar syntax as would be used with the standard input cin. e.g.
1
2
int n;
infile >> n;  // read an integer from the file 


You need to do two additional things.
a) test whether or not the file access was successful.
b) use some sort of loop to process all of the items in the file.

Typically you'd use a while loop, to do both of those things in a fairly straightforward way. See for example the section on text files in the tutorial
http://www.cplusplus.com/doc/tutorial/files/

Nov 13, 2015 at 2:58pm
Thanks so much! I honestly wasn't expecting someone to answer me so fast. Upvotes to you, good sir.
Topic archived. No new replies allowed.