ris*_*iag 7 c++ string getline
基本上我首先采用整数作为输入然后测试用例.我的每个测试用例都是一个字符串.如果字符串的起始模式匹配"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
小智 6
ignore()函数可以解决问题。默认情况下,它会丢弃所有的输入序列,直到换行符为止。
也可以指定其他分隔符和char限制。
http://www.cplusplus.com/reference/istream/istream/ignore/
在您的情况下,它是这样的。
    cin >> N;
    cin.ignore();
您将cin >>N停在第一个非数字字符,即换行符。这是您必须getline阅读的内容,很好。
之后的每个附加getline内容将读取整行,包括末尾的换行符。一秒钟,getline您将跳过一半的输入。
| 归档时间: | 
 | 
| 查看次数: | 26500 次 | 
| 最近记录: |