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

C++ Using std::getline in place of cin >>

本文关键字:gt cin getline 使用 std C++ 代替      更新时间:2023-10-16

在一个问题中,我必须接受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个输入。不知道为什么?

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

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

这段代码应该可以运行

#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;
}