I need to reverse the order of the file and outputted into another file. For example, the
input:
hello
this is a testing file again
just so much fun
Expected output:
just so much fun
this is a testing file again
hello
This is my current code, it printed to where it reverses the order of the lines but also the order of the characters of each word.
Current:
nuf hcum os tsuj
niaga elif gnitset a si siht
olleh
int print_rev(string filename, char c){
ifstream inStream (filename);
ofstream outStream;
inStream.seekg(0,inStream.end);
int size = inStream.tellg();
outStream.open("output.txt");
for (int j=1; j<=size; j++){
inStream.seekg(-j, ios::end);
c=inStream.get();
outStream << c;
}
inStream.close();
outStream.close();
return 0;
}
You're reversing the whole file, character by character. What you want to do is read in each line separately, and then reverse the line order.
A stack of lines seems like a good choice for this :
int printRev(string filename)
{
stack<string> lines;
ifstream in(filename);
string line;
while (getline(in, line))
{
lines.push(line);
}
ofstream out("output.txt");
while (!lines.empty())
{
out << lines.top() << endl;
lines.pop();
}
return 0;
}
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.