如何正确读取文本文件中的单词并颠倒偶数单词的顺序



很抱歉不够清晰,英语是我的第二语言,有时很难指定我需要什么。

我有一项任务要写一个c++程序,它:(1(读取一个文本文件,确定哪些单词是偶数,哪些单词是奇数(2(然后取偶数单词,并颠倒每个偶数单词中的字符顺序。

例如,我有一个中等大小的文本。它挑选出偶数个单词,并颠倒它们的字符顺序。

到目前为止,我已经写了这段代码,我不知道继续写下去是否有什么好处,因为我不知道如何颠倒字符的顺序。谢谢你的帮助。

#include <iostream>
#include <string>
#include <string.h>
#include <cstdlib>
#include <fstream>
using namespace std;
int main()
{
string word;
ifstream f("text.txt");
if (f.is_open())
{
while (f >> word)
{
if (word.length() % 2 == 0)
cout << word << endl;
}
f.close();
}
else
cout << "file is not open" << 'n';
}

您只需要将std::reverse添加到代码中。我还查看了您的代码片段。

在那之后,你的代码会看起来像这样:

#include <iostream>
#include <string>
// #include <string.h> -- no need of this header
#include <cstdlib> // not required at all for this code segment, maybe required in your actual code
#include <fstream>
#include <algorithm> // this is additional header that you need
using namespace std; // this is not a good practice though
int main()
{
string word;
ifstream f("text.txt"); // it is not recommended to use single letter variable names
if (f.is_open()) // just keeping f instead of f.is_open() will work the same way
{
while (f >> word)
{
if (word.length() % 2 == 0)
cout << reverse(word.begin(), word.end()) << endl; // using std::reverse here
}
f.close(); // not necessary statement but considered a good practice to prevent memory leaks and access locks.
}
else
cout << "file is not open" << 'n'; // prefer using std::cerr instead of std::cout to log errors
// and better error message will be "Unable to open text.txt!".
return 0; // return something other than 0 in case of error
}

如果你想冒险一点,你可以使用正向和反向迭代器编写自己的简单字符串反向函数,并简单地交换中间字符串两端的字符,例如

std::string& strrev (std::string& s)
{
std::string::iterator i = s.begin();
std::string::reverse_iterator j = s.rbegin();
for (; &(*j) > &(*i); i++, j++) {
unsigned char tmp = *i;
*i = *j;
*j = tmp;
}
return s;
}

当然,std::reverse()为您做到了这一点,但正如@john在评论中指出的那样,能够发明代码来解决问题就是编程的全部。

最新更新