string类 方法
可以进行string对象或和c风格字符串之间'<' '>' '==' '!='比较
*************************************************************
size() length() 返回字符串长度
*************************************************************
find()
//*pos都表示 从字符串pos个字符开始查找*//
1>find(const string & str,size_type pos=0)
返回str字符串首次出现索引 否则返回string::npos
2>find(const char *s,size_type pos=0)
返回字符串s首次出现索引 否则返回string::npos
3>find(const char *s,size_type pos=0,size_type n)
返回字符串s前n个字符首次出现索引 否则返回string::npos
4>find(char ch,size_type pos=0) const
返回字符ch首次出现索引 否则返回string::npos
rfind("str")
查找字符或字符串最后一次出现的位子返回索引
find_first_of("str")
返回字符串中查找首个在参数中的字符的位子
find_last_of("str")
返回字符串中查找最后个在参数中的字符的位子
find_first_not_of("str")
返回在字符串中查找首个不在参数中的字符的位子
find_first_not_of("str")
返回在字符串中查找最后一个不在参数中的字符的位子
//
做个判断
while(判断)
{
……
判断 以便判断是否循环
}
******************************************************************
读入
while(读入是否成功或是否达到结束要求)
{
……
读入
}
//////////////////////////////////////////////////////
//
//guessword.cpp
//
/////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cctype>
using std::string;
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()
{
using namespace std;
srand(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];
int length = target.length();
string attempt(length, '-');
string badchars;
int guesses = 6;
cout << "Guess my secret word. It has " << length
<< " letters, and you guess\n"
<< "one letter at a time. You get " << guesses
<< " wrong guesses.\n";
cout << "Your word: " << attempt << endl;
while (guesses > 0 && attempt != target)
{
char letter;
cout << "Guess a letter: ";
cin >> letter;
if (badchars.find(letter) != string::npos
|| attempt.find(letter) != string::npos)
{
cout << "You already guessed that. Try again.\n";
continue;
}
int loc = target.find(letter);
if (loc == string::npos)
{
cout << "Oh, bad guess!\n";
--guesses;
badchars += letter; // add to string
}
else
{
cout << "Good guess!\n";
attempt[loc]=letter;
// check if letter appears again
loc = target.find(letter, loc + 1);
while (loc != string::npos)
{
attempt[loc]=letter;
loc = target.find(letter, loc + 1);
}
}
cout << "Your word: " << attempt << endl;
if (attempt != target)
{
if (badchars.length() > 0)
cout << "Bad choices: " << badchars << endl;
cout << guesses << " bad guesses 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;
}


浙公网安备 33010602011771号