我从名为test.txt
的文本文件中读取数据。文件内容:
C ++每天都在困扰我
而且我想要一个类似的结果,
++ C si gnibrutsid yreve yad(反义词)
[我是C ++的每一天都令人不安(排序)
我该怎么办?这是我尝试过的:
#include <fstream>
#include <iostream>
#include <vector>
using namesapce std;
string file { "test.txt" }
int main()
{
ifstream in(file);
vector<char> v{istreambuc_iterator<char>(in), istreambuf_iterator < char()};
/* my horrible coding
int n{ 0 };
for (auto i = v.cbegin(); i < v.cend(); ++i)
{
int tmp=0;
if (*i == ' ')
{
v[n] = tmp;
v[n] = *i;
tmp = *i;
}n++;
}
--------------------*/
for (auto c : v) cout << c;
}
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
void printReversedWords(std::vector<std::string> const& vec) noexcept {
for (auto const& str : vec) {
std::copy(str.crbegin(), str.crend(),
std::ostream_iterator<char>(std::cout));
std::cout << ' ';
}
std::cout << '\n';
}
void printSortedVec(std::vector<std::string> vec) noexcept // pass by copy
{
std::sort(vec.begin(), vec.end());
for (auto const& str : vec) std::cout << str << ' ';
std::cout << '\n';
}
int main()
{
auto constexpr fileName = "./test.txt";
std::ifstream in(fileName);
if (!in) {
std::cerr << "Failed to open the file";
return -1;
}
std::vector<std::string> const vec{std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>()};
printReversedWords(vec);
printSortedVec(vec);
}