C++ Primer Plus第六版 第十六章 编程练习答案

迭代器有点晕...


//第一题
//main.cpp
#include <iostream>
#include <string>

bool palindrome(const std::string &str);

int main()
{
	std::string str;
	std::cin >> str;
	std::cout << (palindrome(str) ? "是" : "否") << std::endl;

	return 0;
}

bool palindrome(const std::string &str)
{
	for (int begin = 0, end = str.size() - 1; begin < end; ++begin, --end)
	{
		if (str[begin] != str[end])
			return false;
	}
	return true;
}



//第二题
//main.cpp
#include <iostream>
#include <string>
#include <cctype>

void simplify(std::string &str);

bool palindrome(const std::string &str);

int main()
{
	std::string str;
	std::getline(std::cin, str);

	simplify(str);

	std::cout << (palindrome(str) ? "是" : "否") << std::endl;

	return 0;
}

void simplify(std::string &str)
{
	std::string temp;
	for (int i = 0; i < (int)str.size(); ++i)
	{
		if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
			temp.push_back(tolower(str[i]));
	}
	str = temp;
}

bool palindrome(const std::string &str)
{
	for (int begin = 0, end = str.size() - 1; begin < end; ++begin, --end)
	{
		if (str[begin] != str[end])
			return false;
	}
	return true;
}




//第三题
//main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>

const int NUM = 26;
const std::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()
{
	std::srand(std::time(0));

	std::vector<std::string> input;
	
	std::ifstream fin;
	fin.open("data.txt");
	std::string temp;
	while (fin >> temp)
		input.push_back(temp);

	while (!input.empty())
	{
		std::string target = wordlist[std::rand() % NUM];
		int length = target.length();
		std::string attempt(length, '-');
		std::string badchars;
		int guesses = 6;
		std::cout << "Guess my secret word. It has " << length << " letters, and you guess\n" << "one letter at a time. You get " << guesses << " wrong guesses.\n";
		std::cout << "Your word: " << attempt << std::endl;
		int count = -1;
		while (guesses > 0 && attempt != target && count < (int)input[0].size())
		{
			++count;
			std::cout << "Guess a letter: ";
			if ((badchars.find(input[0][count]) !
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值