首页 > 解决方案 > 如何正确读取文本文件中的单词并反转偶数单词的顺序?

问题描述

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

我有一个任务要编写一个 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';
    }

标签: c++

解决方案


您只需要添加到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
}

推荐阅读