c++ - Getline 不断获取换行符。我怎样才能避免这种情况?

标签 c++ string getline

基本上我首先将一个整数作为输入,然后是测试用例。我的每个测试用例都是一个字符串。如果字符串的起始模式匹配“HI A”并且不区分大小写,我想打印回字符串。我写了下面的代码来完成这个。我的问题是,当我在每次输入后按回车键时,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

最佳答案

ignore() 函数可以解决问题。默认情况下,它会丢弃所有输入序列,直到换行符。

也可以指定其他分隔符和字符限制。

http://www.cplusplus.com/reference/istream/istream/ignore/

在你的情况下它是这样的。

    cin >> N;
    cin.ignore();

关于c++ - Getline 不断获取换行符。我怎样才能避免这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18725522/

相关文章:

python - 如何在python中删除字符串中任意位置的字母?

string - 有没有像 "firstIndexOf"这样的代码?

在 C 中使用 strcpy 将函数中的单词复制到字符串?

c++ - 运行程序时它让我在名称后输入两行?请帮助

c++ - 如何正确使用getline

检查 stdin 中读取的行格式为 number^number

c++ - 在 Android 发送的图像上计算服务器端的 OpenCV 函数

c++ - 无法获得箭头键的正确值

c++ - GNU make 忽略隐式规则

c++ - 为什么使用静态数组而不是动态数组?