gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:59 24 4
gpt4 key购买 nike

在一个问题中,我必须将 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 来读取换行符,然后将其丢弃以定位到下一行的开头。

关于C++ 使用 std::getline 代替 cin >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com