選択した入力方法 ( cin >> ch
) によって、入力が自動的に個別の単語に分割されます。ジェリー・コフィンが答えで言ったように、句読点などをスキップして、交換するアルファ文字を見つける必要があります。おおよそ次のようになります。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string ch;
while (cout << "String? " && cin >> ch)
{
cout << "Input: <<" << ch << ">>\n";
const char *bp = ch.c_str();
const char *ep = ch.c_str() + ch.length() - 1;
const char *sp = ch.c_str();
while (sp < ep)
{
while (sp < ep && (*sp != ' ' && !isalpha(*sp)))
sp++;
while (sp < ep && (*ep != ' ' && !isalpha(*ep)))
ep--;
char c = *sp;
ch[sp-bp] = *ep;
ch[ep-bp] = c;
sp++;
ep--;
}
cout << "Output: <<" << ch << ">>\n";
}
cout << endl;
return 0;
}
会話例
String? How are you?
Input: <<How>>
Output: <<woH>>
String? Input: <<are>>
Output: <<era>>
String? Input: <<you?>>
Output: <<uoy?>>
String? Pug!natious=punctuation.
Input: <<Pug!natious=punctuation.>>
Output: <<noi!tautcnu=psuoitanguP.>>
String?
ここから微調整できます。これが慣用的な C++ であるとは言いません。const char *
真ん中の の使用は、私の C のバックグラウンドを示しています。