C++ 使用 std::getline 代替 cin >>
C++ Using std::getline in place of cin >>
在一个问题中,我必须接受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;
}
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- EASTL矢量<向量<int>>连续的
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- 将 cin 限制为只有一个
- cin >> int 给定一个字符串将 int 赋值为 0
- istream std::cin如何修改自定义istream缓冲区
- C++ 将 CIN 值存储到任何类型的数组中
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- cin 的十进制输入验证?
- Turbo C++ cin() 不能与 gets() 一起使用
- 使用 cin 时接受小数点后的 2 位数字
- 在 std::getline 和 std::cin 期间卡在循环中
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- C++ cin.ignore() 跳过循环
- CIN是逻辑1还是0?
- 如何运行多行 cin?