C ++使用std :: getline代替cin>>

时间:2015-08-24 00:27:48

标签: c++

在一个问题中,我必须将n个字符串作为输入并计算包含给定子字符串的字符串(不区分大小写)。

这是我的代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
int main()
{
    std::string str2 = "hello";
    std::string str3 = "HELLO";
    short int n,count=0,i;
    cin>>n;
    std::string str1[n];
    for(i=0;i<n;i++)
    {
        std::getline(std::cin,str1[i]);   //here getline is taking only n-1  inputs
        std::size_t found1=str1[i].find(str2);
        std::size_t found2=str1[i].find(str3);
        if(found1!=std::string::npos || found2!=std::string::npos)
            count++;
    }
    cout<<count;
    return 0;
}

由于我不能使用cin作为字符串包含空格或cin.getline(),因为必须使用字符串类型代替char []。
我的代码问题是std :: getline()只接受n-1输入。可以找出原因吗?

2 个答案:

答案 0 :(得分:4)

cin之后的第一个getline读取该行的剩余部分,这可能是空的。这就是为什么在阅读用户输入时,通常最好使用代码来使用getline和进程输入。

cin >> n之后,输入流位于数字n之后。您可以使用getline来读取换行符,然后将其扔掉以定位到下一行的开头。

答案 1 :(得分:0)

此代码应该可以使用

#include <iostream>
#include <string>

using namespace std;

int main() {
    int n = 0, count = 0;
    cin >> n;

    do {
        string str;
        getline(cin, str);

        if (str.find("HELLO") != string::npos || str.find("hello") != string::npos) {
            count++;
        }
    } while (n-- && n >= 0);

    cout << count << endl;
    return 0;
}
相关问题