|
我预先设定了一个数组char result[]="Best regards", 让用户猜,
然后用cin.get()接收用户输入,并用用户输入的内容组成一个新的数组input [11],
然后逐个比较用户输入的每个字符。
我设置了循环结构,使用户可以试多次,第一次输入Best regards,程序认为用户输入正确,第二次输入相同的内容,程序却认为错误,为什么?
- #include<iostream>
- #include<string>
- using namespace std;
- const int size = 11;
- void min ();
- void try_again ();
- int main () {
- cout << "First, please let me say: best regards to you."
- <<
- "The program is run to guess a clase that conains eleven letter. Only the first one is capital."
- << "You could type eleven letters followed by enter." <<
- "Okay, now, give it a go->:" << endl;
- min ();
- }
- void min () {
- char input[size];
- char result[] = "Best regards";
- char c;
- cout << "looping ";
- for (int i = 0; i < size; i++) //initialize the array
- cin.get (input[i]);
- for (int i = 0; i < size; i++) //compare with the result
- if (input[i] == result[i])
- cout << "The " << i << "th letter is good." << endl;
- else
- cout << "Sorry for the " << i << "th letter." << endl;
- cin.ignore (); //the cin is used to filter extra letters
- cout << "Do you want ot try again, yet? y for yes, n for no." << endl;
- try_again ();
- }
- void try_again () {
- char s;
- cin >> s; //the cin is used to filter extra letters
- if (s == 'y')
- min ();
- else if (s == 'n')
- exit (0);
- else
- {
- cout << "Please enter y, or n:";
- try_again ();
- }
- }
复制代码 |
|