第一个代码是错的,是错的,是错的; 看第二个代码。
#include <iostream> #include<string> using namespace std; int main() { int num,temp=0,record[10]={0}; char ctemp; string ans[2]={"NO","YES"}; cin>>num; cin.get();//去回车 for(;temp<num;++temp) { ctemp=cin.get(); while(ctemp=='A') ctemp=cin.get(); if(ctemp=='P') { if(cin.get()=='A') { ctemp=cin.get(); if(ctemp=='T') record[temp]=1; else if(ctemp=='A'&&cin.get()=='T') record[temp]=1; } } ctemp=cin.get(); while(ctemp!='\n') { if(ctemp!='A') record[temp]=0; ctemp=cin.get(); } } for(temp=0;temp<num;++temp) cout<<ans[record[temp]]<<endl; return 0; }我对题目的理解就错了。所以以上代码只符合我自己的理解,并不通用。
暴露的问题: 1、对于多个字符输入,回车的处理不熟悉(要借鉴别人的代码、刷题、查资料来提升) 2、注重初始化,此问题导致程序崩溃许久
cin cin.get() cin.getline() getline() gets() getchar() 这几类的区别
//——————2017年4月1日 15:24:25—————————–// 刷完PAT乙级70题,回头来解决这题啦
#include<iostream> #include<cstdio> #include<string> using namespace std; int main() { int n; string str[10]; cin >> n; cin.get(); for (int i = 0; i < n; ++i) { getline(cin, str[i]); } for (int i = 0; i < n; ++i) { int p = 0, t = 0; int cnt_p = 0, cnt_t = 0; int flag = 0; for (int j = 0; j < str[i].size(); ++j) { if (str[i][j] != 'P'&&str[i][j] != 'A'&&str[i][j] != 'T')//有PAT以外的符号,NO; { flag = 1; break; } else if (str[i][j] == 'P')//统计P个数并记录位置; { cnt_p++; p = j; } else if (str[i][j] == 'T')//统计T个数并记录位置; { cnt_t++; t = j; } } //如果有其他符号,或者P、T不等于1个,或者T、P间没A,或者T在P前面,或者A个数不符合规则,NO; if (flag==1||cnt_p != 1 || cnt_t != 1 || t-p <2 || p*(t - p - 1) != (str[i].size() - t - 1)) { cout << "NO" << endl; continue; } cout << "YES" << endl; } system("pause"); return 0; }回头解决这题虽然是得心应手,一次通过,但是不够简洁。 以上删改后的代码是参考了前辈后改的:http://blog.csdn.net/wyxdexyq/article/details/23255135