必須創建我們自己的函式來接收來自輸入檔案的句子/句子。然后它應該單獨反轉每個單詞的字母,并保持明文中的所有其他(非字母)字符不變,即“貓坐在墊子上!” 將變為“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 ;
}
}
uj5u.com熱心網友回復:
所以這里的代碼可以從輸入檔案中輸出句子,每個單詞都被反轉,然后所有這些單詞按照它們在句子中的順序輸出到一個句子中。它還有一些問題,比如如果單詞中有一個非字母字符,在前面或結尾之前的某個地方,那個字符會被推到單詞的后面,所以這個需要改進。如果有的話,請隨意添加建設性的批評。但是,認為這仍然提供了原始問題。謝謝大家的幫助。
#include <fstream>
#include <string>
#include <sstream>
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)){ //get sentence from input line
reverse(input); //Reverse the sentence
cout << endl; //end line for next sentence
}
inData.close();
outData.close();
return 0;
}
void reverse(string input){
string nonAlpha = "";
bool end = false;
bool nonLetter = true;
while(end != true){
int idx = input.find(" "); //Finds index of blank space
int lastIdx = input.size(); //Finds the last index
if(idx <= 0){ //If it is the last index, then that becomes idx
idx = lastIdx;
end = true;
}
string word = input.substr(0, idx); //Word usually starts from index 0, until the blank space
string x;
for (int i = idx-1; i >= 0; i--){ //Then outputs each letter according to the index of the word
// but starts from last index and decrements thereby reversing the word
if((isalpha(word.at(i))==false)){ //If that index is not a letter then it is stored and will be outputted after word
nonAlpha.push_back(word[i]); //However this can be a problem for non-letter if not at end of word
nonLetter = true;
}
else{
x= word.at(i);
cout << x; //Prints the letter
}
}
if(nonLetter == true){
cout << nonAlpha; //Prints the non-letter
nonAlpha.erase(); //Erases whatever is inside for future non-letters
nonLetter = false; //Makes it false and will be used agaian when there is another non-letter
}
cout << " "; //Space between words
input.erase(0,idx 1); //Erases word when finished reversing and outputting it so can start next word
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488821.html
上一篇:列印單個字符的二進制表示
下一篇:有沒有辦法將串列轉換為字串?
