Getting an error trying to compile the following bit of code:
Kind of stuck needing to use the getline function vs using extraction or insertion operators. Not really sure what I'm doing wrong but I know it must not be proper syntax.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
string filename;
ifstream inFile;
ofstream outFile;
int num;
line = "No Value";
filename = "No Value";
num = -1;
inFile.open("in1.txt");
outFile.open("out.txt");
getline(inFile,outFile);
return 0;
}
Basically, I just want it to take the line from the infile, and output it to the outfile. But I need to use getline.
FileIO_2.cpp:24:24: note: 'std::ofstream {aka
std::basic_ofstream<char>}' is not derived from
'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>'
getline(inFile,outFile);
Change this part of code:
getline(inFile,outFile);
To this one:
getline(inFile, line); // get the line from "inFile" and output it to the variable "line"
outFile << line; // write "line" variable data to "outFile"
// another way is: outFile.write(line.c_str(), line.size());
getline
expects an input file and output string
variable, and not output file. Read more about getline
here: https://en.cppreference.com/w/cpp/string/basic_string/getline
There are unused variables, that it seems like you should use them. filename
probably should be use as 'input'/'output' files name, and maybe it will be even better to add another variable that will store the other file name. int num
looks useless in this context. Your code might look better in the following form:
string line, input_filename, output_filename;
ifstream inFile;
ofstream outFile;
input_filename = "in1.txt";
output_filename = "out.txt";
inFile.open(input_filename);
outFile.open(output_filename);
getline(inFile, line);
outFile << line;
getline
expects a string as it's 2nd argument, but you have given it a stream.
Read from the input file into the string, then write the string to your output file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.