Outputting the reversal of a string?
Feb 11, 2015 at 3:36pm UTC
Hello, I am having trouble with a certain part of my assignment. I am supposed to take strings from a .txt file and reverse the the order and then output it. I don't have much on this portion of the assignment but here is what I have.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
/////////------------------/////////
//Function Prototypes//
int fileLength();
string reverseString();
/////////------------------/////////
int main()
{
ifstream inFile;
inFile.open("Chapter 10 C++ Text File.txt" );
string item;
int count = 0;
int length = 0;
fileLength();
reverseString();
while (!inFile.eof())
{
inFile >> item;
count++;
length += item.length();
}
}
int fileLength() //Determines and returns the number of characters in the string.
{
ifstream inFile;
inFile.open("Chapter 10 C++ Text File.txt" );
string item;
int count = 0;
int length = 0;
while (!inFile.eof())
{
inFile >> item;
count++;
length += item.length();
}
cout << "Length of characters in this file: " << length << endl;
}
string reverseString() //Outputs the string backwards
{
ifstream inFile;
inFile.open("Chapter 10 C++ Text File.txt" );
int count = 0;
string item, reverse;
while (!inFile.eof())
{
inFile >> item;
count++;
reverse += item;
}
cout << "Backwards: " << item << endl;
}
Thanks for any help ^-^
Feb 11, 2015 at 4:58pm UTC
Do you mean reverse the order of lines? Or reverse each individual line, but keep the order the same?
Feb 12, 2015 at 4:04pm UTC
I would really like to reverse each individual line but keep the order the same.
Feb 12, 2015 at 4:40pm UTC
This will return the reverse of it's argument.
1 2 3 4 5 6
string reverse_string(const string & original)
{
string reverse("" );
for_each(original.rbegin(), original.rend(), [&reverse](auto c) {reverse += c;});
return reverse;
}
Feb 12, 2015 at 6:23pm UTC
Slightly shorter version of tipaye's.
1 2 3 4
string reverse_string(const string & original)
{
return {original.rbegin(), original.rend()};
}
Feb 12, 2015 at 6:36pm UTC
@naraku9333
Nice, very nice!
Topic archived. No new replies allowed.