發問時間: 電腦與網際網路程式設計 · 4 年前

C++程式設計幾個問題?

3.試撰寫一程式,由鍵盤輸入一字串,並傳遞該字串到reverse()函數,將字串以前後顛倒的順序重新排列後,再於主程式中印出來。舉例來說,輸入的字串為"milk",輸出即為"klim"。

5.試撰寫一程式,由鍵盤輸入2個字串,分別印出字串的長度,並判別這2個字串是否相同。

6.試撰寫一程式,利用assign() 函數為2個字串分別設值 "Practice makes perfect"、"Haste makes waste",再利用compare() 函數判別這2個字串是否相同。

請問這3題該怎麼打

1 個解答

評分
  • 4 年前
    最佳解答

    #include<ctype.h>

    #include<iostream>

    using namespace std;

    int length(

    string s

    ){

    int ret;

    for(ret=0;s[ret];++ret);

    return ret;

    }

    string reverse(

    const string s

    ){

    string ret = s;

    int i,j;

    i = length(s);

    for(--i,j=0,ret=s;i>=0;ret[j++]=s[i--]);

    return ret;

    }

    bool compare(

    string s0,

    string s1

    ){

    return s0==s1;

    }

    int main(void){

    string s0 = "milk";

    cout << "The reverse of "<< s0 << " is "<< reverse(s0) << '.' << endl;

    string s1, s2;

    cout << "Enter s1:"; cin >>s1;

    cout << "Enter s2:"; cin >>s2;

    cout << "S1 \"" << s1 << "\" of length=" << length(s1) << endl;

    cout << "S2 \"" << s2 << "\" of length=" << length(s2) << endl;

    cout << "And they are " << (compare(s1,s2) ? "the same." : "different.")<<endl;

    s1 = "Practice makes perfect";

    s2 = "Haste makes waste";

    cout << "S1 \"" << s1 << "\" of length=" << length(s1) << endl;

    cout << "S2 \"" << s2 << "\" of length=" << length(s2) << endl;

    cout << "And they are " << (compare(s1,s2) ? "the same." : "different.")<<endl;

    return 0;

    }

還有問題?馬上發問,尋求解答。