-4

例:お元気ですか?----> woh の時代の uoy?

これは私のコードです。うまくいきましたが、疑問符も逆になっています。どうすれば無傷のままにできますか?

#include <iostream>
using namespace std;
int main()
{
    string ch;
    while(cin >> ch)
    {
         for(int i = ch.length() - 1; i >= 0; i--)
         {
             cout << ch[i];
         }
         cout << " ";
    }
    return 0;
}
4

4 に答える 4

2

選択した入力方法 ( 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 のバックグラウンドを示しています。

于 2013-10-26T05:34:11.153 に答える
1

文字列の先頭から開始し、文字が見つかるまで順方向にスキャンします。文字が見つかるまで、最後から逆方向にスキャンします。それらを交換します。2 つの位置が一致するまで続行します。

注: 上記では「文字」を使用しましたが、実際に意味するのは「逆にする必要がある文字の 1 つ」です。あなたはどの文字を交換すべきでどの文字を交換すべきでないかを正確に定義していませんが、あなた (またはあなたの教師) はかなり具体的な定義を念頭に置いていると思います。

于 2013-10-26T05:28:03.210 に答える
0

このケースを単独で解決するための簡単な解決策またはハック。さらに多くのケースがコメントされている場合は、一緒に解決できます。

#include <iostream>
using namespace std;
int main()
{
    string ch;
    while(cin >> ch)
    {
        int flag = 0;
        for(int i = ch.length() - 1; i >= 0; i--)
        {
                if(ch[i] != '?')
                        cout << ch[i];
                else
                        flag = 1;
        }
        if(flag)
                cout << "?";
        else
                cout << " ";
    }
    return 0;
}
于 2013-10-26T05:36:45.803 に答える