i am required to reverse the order of the letters of words in the string but the position of punctuation and the words must stay the same. eg.
The dog is big. That is a big dog.
i am supposed to get :
ehT god si gib. tahT si a gib god.
but i get:
#include <iostream>
#include <string>
#include <algorithm>
using std::cout;
using std::endl;
using std::string;
using std::swap;
int main()
{
string text = "The dog is big. That is a big dog.";
int length = text.length();
for (int i = 0; i < length / 2; i++)
swap(text[i], text[length - i - 1]);
cout << text;
return 0;
}
#include <iostream>
#include <string>
#include <algorithm>
using std::cout;
using std::endl;
using std::string;
using std::swap;
int main()
{
string text = "The dog is big. That is a big dog.";
reverse(text.begin(), text.end());
cout << text;
return 0;
}
I'm trying to read multiple lines from a file and reverse all the lines
input:
Expecting the world to treat you
fairly because you are a good person
is a little like expecting the bull not to
attack you because you are a vegetarian.
output:
kcatta uoy esuaceb uoy era a nairategev.
which is only the last line. how can i correct this?
Just open the file in main() and leave it open, passing the ofstream as a reference parameter to revWord().
Alternatively, you could let revWord build up a word-reversed string and return that.
Your problems are that:
(1) You are opening and rewriting the file for every line;
(2) You didn't say this was what you wanted to do in your initial post.
#include <string>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cctype>
void backword(std::ostream& os, const std::string& line)
{
std::istringstream iss(line);
for (std::string wrd; iss >> wrd; ) {
constauto ed {std::find_if(wrd.crbegin(), wrd.crend(), [](unsignedchar ch) { return !std::ispunct(ch); })};
os << std::string(ed, wrd.crend()) << std::string(ed.base(), wrd.cend()) << ' ';
}
os << '\n';
}
int main()
{
std::ifstream ifs("input.txt");
std::ofstream ofs("output.txt");
if (!ifs || !ofs)
return (std::cout << "Cannot open files\n"), 1;
for (std::string line; std::getline(ifs, line); backword(ofs, line));
}
gnitcepxE eht dlrow ot taert uoy
ylriaf esuaceb uoy era a doog nosrep
si a elttil ekil gnitcepxe eht llub ton ot
kcatta uoy esuaceb uoy era a nairategev.