《C++ Primer Plus(第六版)》(36)(第十六章 string类和标准模板库 编程练习和答案)

16.10 编程练习

1.回文指的是顺着读和逆着读都一样的字符串。假如,“tot"和“otto”都是简短的回文。编写一个程序,让用户输入字符串,并将字符串引用传递给一个bool函数。如果字符串是回文,该函数将返回true,否则返回false。此时,不要担心诸如大小写、空格和标点符号这些复杂的问题。即这个简单的版本将拒绝“Otto”和“Madam,I'm Adam”。请查看附录F中字符串方法列表,以简化这项任务。

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include "Test.h"
using namespace std;
using namespace FableGame;

bool check(const string& str)
{
    string temp = str;
    reverse(temp.begin(), temp.end());
    return str == temp;
}


int main()
{
    cout << "Enter a Palindrome: ";
    string str;
    while (cin >> str) {
        if (check(str)) {
            cout << str << " is Palindrome" << endl;
        }
        else
        {
            cout << str << " is not Palindrome" << endl;
        }
        cout << "Enter a Palindrome: ";
    }
    return 0;
}

2.与编程练习1中给出的问题相同,但要考虑诸如大小写、空格和标点符号这样的复杂问题。即“Madam, I‘m Adam”将作为回文来测试。例如,测试函数可能会将字符串缩略为“madamimadam”,然后测试倒过来是否一样。不要忘了有用的cctype库,您可能从中找到几个有用的STL函数,尽管不一定非要使用它们。

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include "Test.h"
using namespace std;
using namespace FableGame;

bool check(const string& str)
{
    string temp0;
    for (int i = 0; i < str.length(); i++) {
        if (islower( str[i] )) {
            temp0.push_back(str[i]);
        }
        else if(isupper(str[i]))
        {
            temp0.push_back(tolower(str[i]));
        }
    }
    string temp = temp0;
    reverse(temp.begin(), temp.end());
    return temp0 == temp;
}


int main()
{
    cout << "Enter a Palindrome: ";
    string str;
    
    while ( cin && getline(cin, str)) {
        
        if (check(str)) {
            cout << str << " is Palindrome" << endl;
        }
        else
        {
            cout << str << " is not Palindrome" << endl;
        }
        cout << "Enter a Palindrome: ";
    }
    return 0;
}

3.修改程序清单16.3,使之从文件中读取单词。一种方案是,使用vector<string>对象而不是string数组。这样便可以使用push_back()将数据文件中的单词复制到vector<string>对象中,并使用size()来确定单词列表的长度。优于程序应该每次从文件中读取一个单词,因此应该使用>>而不是getline()。文件中包含的单词应该用空格、制表符或换行符分隔。

原来的程序:程序清单16.3

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include "Test.h"
using namespace std;
using namespace FableGame;

const int NUM = 26;
const string wordlist[NUM] = {
    "apiary", "beetle", "cereal", "danger",
    "ensign", "florid", "garage", "health",
    "insult", "jackal", "keeper", "loaner",
    "manage", "nonce", "onset", "plaid",
    "quilt", "remote", "stolid", "train",
    "useful", "valid", "whence", "xenon",
     "yearn", "zippy"
};

int main()
{
	
    srand((int)time(0));
    char play;
    cout << "Will you play a word game?<y/n> ";
    cin >> play;
    play = tolower(play);
    while ( play == 'y') {
        string target = wordlist[rand() % NUM];
        size_t length = target.length();
        string attemp(length, '-');
        string badchars;
        int guesses = 6;
        cout << "Guess my secret word. Is has " << length
            << " letters, and you guess\none lettle at a time. You get " << guesses << " wrong guesses.\n";
        
        cout << "Your word: " << attemp << endl;
        while (guesses > 0 && attemp != target) {
            char letter;
            cout << "Guess a letter: ";
            cin >> letter;
            if (badchars.find(letter) != string::npos || attemp.find(letter) != string::npos) {
                cout << "You already guessed that. Try again.\n";
                continue;
            }
            size_t loc = target.find(letter);
            if (loc == string::npos) {
                cout << "Oh, bad guess!\n";
                --guesses;
                badchars += letter;
            }
            else
            {
                cout << "Good guess!\n";
                attemp[loc] = letter;
                loc = target.find(letter, loc + 1);
                while (loc != string::npos) {
                    attemp[loc] = letter;
                    loc = target.find(letter, loc + 1);
                }
            }
            cout << "Your word: " << attemp << endl;
            if (attemp != target) {
                if (badchars.length() > 0) {
                    cout << "Bad choices: " << badchars << endl;
                }
                cout << guesses << " bad guess left\n";
            }
        }
        if (guesses > 0) {
            cout << "That's right!\n";
        }
        else
        {
            cout << "Sorry, the word is " << target << ".\n";
        }
        cout << "Will you play another?<y/n> ";
        cin >> play;
        play = tolower(play);
    }
    
    cout << "Bye\n";
    return 0;
}
修改后的程序:

main.cpp

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "Test.h"
#include <vector>
using namespace std;
using namespace FableGame;

int main()
{
    vector<string> wordlist;
    ifstream ifs;
    ifs.open("/Users/feiyin001/Documents/tttttt.txt");
    string str;
    while (ifs && ifs >> str) {
        wordlist.push_back(str);
    }
    ifs.close();
    
    srand((int)time(0));
    char play;
    cout << "Will you play a word game?<y/n> ";
    cin >> play;
    play = tolower(play);
    while ( play == 'y') {
        string target = wordlist[rand() % wordlist.size()];
        size_t length = target.length();
        string attemp(length, '-');
        string badchars;
        int guesses = 6;
        cout << "Guess my secret word. Is has " << length
            << " letters, and you guess\none lettle at a time. You get " << guesses << " wrong guesses.\n";
        
        cout << "Your word: " << attemp << endl;
        while (guesses > 0 && attemp != target) {
            char letter;
            cout << "Guess a letter: ";
            cin >> letter;
            if (badchars.find(letter) != string::npos || attemp.find(letter) != string::npos) {
                cout << "You already guessed that. Try again.\n";
                continue;
            }
            size_t loc = target.find(letter);
            if (loc == string::npos) {
                cout << "Oh, bad guess!\n";
                --guesses;
                badchars += letter;
            }
            else
            {
                cout << "Good guess!\n";
                attemp[loc] = letter;
                loc = target.find(letter, loc + 1);
                while (loc != string::npos) {
                    attemp[loc] = letter;
                    loc = target.find(letter, loc + 1);
                }
            }
            cout << "Your word: " << attemp << endl;
            if (attemp != target) {
                if (badchars.length() > 0) {
                    cout << "Bad choices: " << badchars << endl;
                }
                cout << guesses << " bad guess left\n";
            }
        }
        if (guesses > 0) {
            cout << "That's right!\n";
        }
        else
        {
            cout << "Sorry, the word is " << target << ".\n";
        }
        cout << "Will you play another?<y/n> ";
        cin >> play;
        play = tolower(play);
    }
    
    cout << "Bye\n";
    return 0;
}

4.编写一个具有老式风格接口的函数,其原型如下:

int reduce(long ar[], int n);

实参应是数组名和数组中的元素个数。该函数对数组进行排序,删除重复的值,返回缩减后数组中的元素数目。请使用STL函数编写该函数(如果决定使用通过的unique()函数,请注意它将返回结果区间的结尾)。使用一个小程序测试该函数。

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "Test.h"
#include <vector>
using namespace std;
using namespace FableGame;

int reduce(long ar[], int n)
{
    sort(ar, ar + n);
    long* p = unique(ar, ar + n);
    return (int)(p - ar);
}
int main()
{
    long a[ 10] = {11, 2, 31, 31, 41, 41, 5, 7, 8, 10};
    
    for (int i = 0; i < 10; ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
    
    int num = reduce(a, 10);
    
    for (int i = 0; i < num; ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
    return 0;
}

5.问题与编程练习4相同,但要编写一个模板函数:

template<class T>

in reduce(T ar[], int n);

在一个使用long实例和string实例的小程序中测试该函数。

//
//  main.cpp
//  HelloWorld
//
//  Created by feiyin001 on 16/12/30.
//  Copyright (c) 2016年 FableGame. All rights reserved.
//
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "Test.h"
#include <vector>
using namespace std;
using namespace FableGame;

template<class T>
int reduce(T ar[], int n)
{
    sort(ar, ar + n);
    T* p = unique(ar, ar + n);
    return (int)(p - ar);
}
int main()
{
    {
        long a[ 10] = {11, 2, 31, 31, 41, 41, 5, 7, 8, 10};
        
        for (int i = 0; i < 10; ++i) {
            cout << a[i] << " ";
        }
        cout << endl;
        
        int num = reduce(a, 10);
        
        for (int i = 0; i < num; ++i) {
            cout << a[i] << " ";
        }
        cout << endl;

    }
    
    {
        string a[ 10] = {"yuandan2017", "fable", "kuaidi", "caonima", "niubi",
            "fancy3d", "fanrenxiuzhen", "fangchangjia", "laosiji", "shuang11"};
        
        for (int i = 0; i < 10; ++i) {
            cout << a[i] << " ";
        }
        cout << endl;
        
        int num = reduce(a, 10);
        
        for (int i = 0; i < num; ++i) {
            cout << a[i] << " ";
        }
        cout << endl;

    }
    return 0;
}


posted @ 2017-01-02 23:11  肥宝游戏  阅读(197)  评论(0编辑  收藏  举报