Hi, I'm having an error when running this program and I don't know what kind of error is it. So hoping someone can help me. Thank You!!

Program: The input file is created with positive and negative numbers. When program ask for the input file it should be the same as the input file name that was created.
Output file is used to store the positive numbers only that was read from the input file. Output file name can be called anything user wants. (Doesn't matter what)

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void pos_num(ifstream input, ofstream output);

int main()
{
	ifstream input;
	string inf;
	ofstream output;
	string outf;
	
	cout << "Enter a name for the input file (ex: val.txt): ";
	cin >> inf;
	cout << "Enter a name for the output file: ";
	cin >> outf;

	input.open(inf);
	output.open(outf);

	if(input.fail() && output.fail())
	{
		cout << "Couldn't open " << inf << " and " << outf << " file" << endl;
		exit(1);
	}

	pos_num(input, output);

	input.close();
	output.close();
	return 0;
}

void pos_num(ifstream input, ofstream output)
{
	int val;
	while(input >> val)
	{
		if(val >= 0)
		{
			output << val << endl;
		}
		else;
	}
}

Copy & Paste

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

void pos_num(ifstream input, ofstream output);

int main()
{
ifstream input;
string inf;
ofstream output;
string outf;

cout << "Enter a name for the input file (ex: val.txt): ";
cin >> inf;
cout << "Enter a name for the output file: ";
cin >> outf;

input.open(inf);
output.open(outf);

if(input.fail() && output.fail())
{
cout << "Couldn't open " << inf << " and " << outf << " file" << endl;
exit(1);
}

pos_num(input, output);

input.close();
output.close();
return 0;
}

void pos_num(ifstream input, ofstream output)
{
int val;
while(input >> val)
{
if(val >= 0)
{
output << val << endl;
}
else;
}
}

Edited 6 Years Ago by aznlitomik3: n/a

lines 21 and 22. open() method takes const char*, not std::string. You have to use string's c_str() to make the conversion. input.open(inf.c_str());

After changing lines 21 and 22 to
input.open(int.c_str());
output.open(outf.c_str());

I'm still getting an error when I'm trying to run the program
Please Help & Thank You!!

line 37: >> void pos_num(ifstream input, ofstream output)

streams have to be passed by reference, not by value as you have done.

This article has been dead for over six months. Start a new discussion instead.