C++ getline()之后的For循环不执行
我可以为getlinecin的调用输入输入,输入“\n”,但它永远不会结束。我可以继续提供意见。我尝试不使用for循环,它接受getline的输入,然后打印它。所以我猜这是for循环的一个问题。我没有编译器错误C++ getline()之后的For循环不执行,c++,for-loop,getline,C++,For Loop,Getline,我可以为getlinecin的调用输入输入,输入“\n”,但它永远不会结束。我可以继续提供意见。我尝试不使用for循环,它接受getline的输入,然后打印它。所以我猜这是for循环的一个问题。我没有编译器错误 #include <iostream> #include <string> using namespace std; int main() { unsigned int i = 0; int cat_appearances = 0; string l
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int i = 0;
int cat_appearances = 0;
string l;
cout << "Please enter a line of text: " << endl;
getline(cin, l, '\n');
for (i = l.find("cat", 0); i != string::npos; i = l.find("cat", i)) {
cat_appearances++;
//move past the last discovered instance to
//avoid finding same string again
i++;
}
cout << "The word cat appears " << cat_appearances
<< " in the string " << '"' << l << '"';
}
打开编译器警告
warning: comparison is always true due to limited range of data type [-Wtype-limits]
for(i = l.find( "cat", 0); i != string::npos; i = l.find("cat",i ))
^
std::string::npos的类型是实现定义的,编译器可能将其定义为std::size\u t,并且在您的平台上sizeofunsigned int另一方面,令人耳目一新的是,您包含了一个完整的、可编译的示例 简单调试:1在循环前用l打印字符串;2打印i的值,或我将得到的值:cout
std::string::size_type i = 0;