【发布时间】:2022-06-12 20:15:09
【问题描述】:
必须创建我们自己的函数来接收来自输入文件的句子/句子。然后它应该单独反转每个单词的字母,并保持明文中的所有其他(非字母)字符不变,即“猫坐在垫子上!”会变成 “ehT tac tas no eht tam!”。 所以我想我找到了一种单独反转单词的方法,但不知道如何找到一种方法在一个句子中输出所有内容。我觉得我需要以某种方式使用数组或向量来帮助存储每个单词,然后最后将所有单词一起输出,但我没有成功。 我还想找到一种方法让它知道何时停止并输出单词之间的空格。
到目前为止,这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void reverse(string input);
int main(){
ifstream inData;
ofstream outData;
string input;
inData.open("input.txt");
outData.open("output.txt");
while(getline(inData, input)){
// cout << input;
outData << input;
}
reverse(input);
inData.close();
outData.close();
return 0;
}
void reverse(string input){
int counter =0;
while(counter != 14){
int idx = input.find(" ");
cout << idx << endl;
string word = input.substr(0, idx);
cout << word << endl;
string x;
for (int i = idx-1; i >= 0; i--)
{
x= word.at(i);
cout << x;
}
cout << endl;
input.erase(0,idx+1);
cout << input << endl;
cout << endl << "new" << endl;
counter++;
}
}
【问题讨论】:
-
这可能需要 7 到 8 行代码来完成,就地,到
input字符串,使用模板、迭代器和算法以相反的顺序留下单词的字母来自 C++ 库。目前尚不清楚您的编程任务来自什么上下文,是否打算让您自己实现所有算法,或者知道如何使用 C++ 库中的算法。无论如何,很遗憾听到您“苦苦挣扎”,但您的具体问题是什么?抱歉,Stackoverflow 不是 C++ 教程网站,我们只回答具体的编程问题。 -
获取单词的一种简单方法是从
getline创建一个std::istringstream,并使用>>运算符将其分解。>>会自动停在空格上,所以你所要做的就是注意标点符号。std::istringstream strm(input); std::string word; std::vector<std::string> words; while (strm >> word) { words.push_back(word); }给出一个单词列表,您可以使用自己的工具或致电std::reverse(words.begin(), words.end()); -
不幸的是,@user4581301,这无法正确保留多个连续的空白。目前还不清楚是否需要完全不触及原始文本字符串,除非所有连续字母都颠倒。如果没有一套完整的具体要求,建议一种方法是没有意义的。
-
字符串必须保持不变,但字母要颠倒。
-
@SamVarshavchik 希望颠倒的词在一个句子中出现,而不是单独出现。
标签: c++ string encryption reverse