c++ - 如何正确读取文本文件中的单词并反转偶数单词的顺序?
问题描述
抱歉,不清楚,英语是我的第二语言,有时很难指定我需要什么。
我有一个任务要编写一个 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
}
推荐阅读
- jenkins - 使用 Kubernetes 集群部署的 Jenkins 管道中由未知权限错误签署的证书
- javascript - 在 Angular 中使用灰度时未定义获取缓冲区
- java - 单应用定制Android ROM
- continuous-integration - Gitlab Ci 在第二个工作之后运行一个工作
- bittorrent - 同行报告但未连接到自托管的 bittorrent 跟踪器
- excel - Excel:如何收集与另一列中的重复项相关联的列中的唯一值?
- asp.net-core - “缺少类型映射配置或不支持的映射。” ASP.NET Core WebApi 中的自动映射异常
- express - 无法在护照 github 策略中删除会话
- javascript - React Native Picker:过滤特定和重复项
- tensorflow-serving - tensorflow_model_server:错误“填充的第一维必须是输入的等级[4,2] ...”