基本上,我首先以整数为输入,然后进行测试用例。我的每个测试用例都是一个字符串。如果字符串的起始模式与“HI A”匹配且大小写不敏感,则应该将字符串打印回来。我编写了下面的代码来完成这个任务。我的问题是,当我在每个输入之后按Enter键时,getline将换行符作为新输入。我尝试通过在每个输入后使用额外的getline来解决这个问题,但问题仍然存在。程序即使我已经设置了退出条件,仍然会被困在循环中。我做错了什么?
#include <iostream>
#include <string>
using namespace std;
int main(){
int N;
cin >>N;
string nl;
getline(cin,nl);
for (int i=0;i<N;i++){
string s;
getline(cin,s);
//cout <<"string"<<s<<endl;
int flag=0;
if ((s.at(0)=='h'||s.at(0)=='H')&&(s.at(1)=='i'||s.at(1)=='I')&&(s.at(2)==' ')&&(s.at(3)=='a'||s.at(3)=='A')) flag=1;
if (flag==1) cout << s;
//cout << "not " <<s;
string ne;
cout << "i="<< i<<endl;
if (i==N-1) {break;}
getline(cin,ne);
}
}
这是样例输入:
5
Hi Alex how are you doing
hI dave how are you doing
Good by Alex
hidden agenda
Alex greeted Martha by saying Hi Martha
输出结果应为:
Hi Alex how are you doing
getline(cin,nl)
更改为cin.ignore()
,以在读取 N 后处理掉该行的其余部分。cin.ignore()
会读取并丢弃从 cin 中仍未读取的该行的其余部分。 - zentrunixtoupper
和tolower
。如果您将字符转换为大写或小写,可以将比较次数减少一半。 - Thomas Matthews