#include<iostream>
#include<fstream>
#include<string>
int ModifyFile(std::ifstream &OutputFile, std::ofstream &InputFile)
{
char StringFromFile[7];
if (OutputFile)
{
OutputFile << "Read this text";
OutputFile.close();
}
if (InputFile)
{
InputFile >> StringFromFile;
std::cout << std::endl << StringFromFile << std::endl;
InputFile.close();
}
return 0;
}
int main()
{
std::string FilePath;
std::cout << "Please enter a file path: ";
std::cin >> FilePath;
std::ifstream OutputFile (FilePath);
std::ofstream InputFile (FilePath);
ModifyFile(OutputFile, InputFile);
return 0;
}
I am trying to create a new file asking user about its path then passing it as an argument to a new in/out - put file and then passing that file as a reference to a ModifyFile function argument in 2 places. Now the main errors the g++ spits out for the ModifyFile are:
main.cpp:11:23: error: no match for ‘operator<<’ in ‘OutputFile << "Read this text"’
and
main.cpp:17:22: error: no match for ‘operator>>’ in ‘InputFile >> StringFromFile’
& for main:
main.cpp:32:39: error: no matching function for call to ‘std::basic_ifstream<char>::basic_ifstream(std::string&)’
and
main.cpp:33:38: error: no matching function for call to ‘std::basic_ofstream<char>::basic_ofstream(std::string&)’
plus other candidates it suggests. Can anyone help me with that program? Thanks!
If you named your ifstream InputFile and named your ofstream OutputFile, you'd find it a lot easier. Right now your input file object is named OutputFile, and your output file object is named InputFile.
As ne555 indicates, and as I thought might become clear once you renamed the two streams, you're trying to read in from an output, and read out to an input.
InputFile << "Read this text";
So you're trying to pass the text "Read this text" to an input stream. That seems foolish. Surely if you want to pass text to something, you should be passing it to the output stream.
OutputFile >> StringFromFile;
So you're trying to read from an output stream. That seems foolish. Surely if you want to read text from something, you should be reading from an input stream.
I'm really sorry but no matter what I do i get the same bloody compilation errors. Can someone tell me which part of code to swap/change. I looked at 2 versions I've posted and both don't work. If i present one you say it's better to rename it. When I rename it you say to change it back because I mixed Input with the output. Help?
The problem was that you're trying to read in from an output, and write out to an input (also, the constructors for ifstream and ofstream don't take string, they take char*). You must read in from the input, and write out to the output. You gave them exactly the wrong names, which then stopped you being able to think about it.