作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我可以为调用 getline(cin, input, '\n') 输入输入,但它永远不会结束。我可以继续提供意见。我试过没有 for 循环,它接受 getline() 的输入然后打印它。所以我的猜测是 for 循环有问题。我没有编译器错误。
#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_t
, 在你的平台上 sizeof(unsigned int) < sizeof(std::size_t)
.
std::string::npos
定义为 std::string::size_type(-1)
,即 std::numeric_limits<size_t>::max()
,在您的平台上无法用 unsigned int
表示的值.
更改 i
到
std::string::size_type i = 0;
(附带说明一下,您包含了一个完整的、可编译的示例,这令人耳目一新!)
关于c++ - getline() 不执行后的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26395116/
我是一名优秀的程序员,十分优秀!