[英]Using getline to read a line from input file to output file
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. 与使用提取或插入运算符相比,需要使用getline函数有点困难。 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. 基本上,我只希望它从infile中提取一行,然后将其输出到outfile。 But I need to use getline. 但是我需要使用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. getline
需要输入文件和输出string
变量,而不是输出文件。 Read more about getline
here: https://en.cppreference.com/w/cpp/string/basic_string/getline 在此处阅读有关getline
更多信息: 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. filename
可能应该用作“输入” /“输出”文件名,也许添加另一个存储另一个文件名的变量会更好。 int num
looks useless in this context. 在这种情况下, int num
看起来毫无用处。 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. getline
需要一个字符串作为它的第二个参数,但是您已经给了它一个流。
Read from the input file into the string, then write the string to your output file. 从输入文件中读取字符串,然后将字符串写入输出文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.