Link to home
Start Free TrialLog in
Avatar of businessesatoz
businessesatoz

asked on

how to read ifstream c++

Hello, how do i correct my code to read from the file that was created  ? ... i want to write a function to do this but i'm not sure how to..

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;
int WriteInts (ofstream &write, int how_many);

int main(void)
{
ifstream in_stream;

ofstream out_stream;


int numbers;
char user_control;
cout <<"Do you wish to R)ead or W)rite ints?";
cin >>user_control;


if(user_control=='w')
{
	
	out_stream.open("nums.txt");
	int numbers;
	int how_many;
	cout <<"how many numbers would you like to type : ";
	cin >> how_many;
	WriteInts(out_stream,how_many);
	
}

else if(user_control=='r')
{
	in_stream.open("nums.txt");
	if(in_stream.fail())
	{
		cout <<"The file does not exist yet";
	}
	

}
else 
{
cout <<"un-regonized commend";
}

}//end of program

int WriteInts (ofstream &write,int how_many)
{
	int numbers;
	for(int i =0; i<how_many;++i)
	{
		
	cout<<"Please enter an Int: ";
	cin >> numbers;
	write << numbers;
	write << endl;
	

	}
	return numbers;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of HooKooDooKu
HooKooDooKu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of businessesatoz
businessesatoz

ASKER

Where does the numbers variable come from I don't see it declared anywhere in this if statement
Actually, it's declared twice.

It's already declared in the original code on line 15.  Then I unnecessarily defined it again just before the "while( true )" statement.  Since you already had it defined at the higher level, I didn't need to redefine it again inside the "else if" block you already created.

Once you define a variable inside a 'block', the variable is valid for the entire block and any child blocks.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I suggest to separate better the opening of the file, closing the file and reading the lines.  For reading the lines, probably the most easy way is to use the function getline() defined in the <string>, like this:

    while (getline(myfile, line))
        count << line << '\n';

Open in new window


Sorry, should be cout instead of count ;)
I've requested that this question be closed as follows:

Accepted answer: 250 points for HooKooDooKu's comment http:/Q_27377793.html#36905906
Assisted answer: 0 points for businessesatoz's comment http:/Q_27377793.html#36906037
Assisted answer: 250 points for hmccurdy's comment http:/Q_27377793.html#36906257

for the following reason:

thanks for the help guys.
i did not mean to close this..
thanks for the help