基本上我首先采用整数作为输入然后测试用例.我的每个测试用例都是一个字符串.如果字符串的起始模式匹配“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
解决方法
你的cin>> N停在第一个非数字字符,即换行符.你有一条读取过去的getline,这很好.
之后的每个附加getline都会读取整行,包括最后的换行符.通过输入第二个getline,你可以省略一半的输入.