[英]For Loop after getline() doesn't execute
我可以輸入對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;
(附帶一提,令人耳目一新的是,您提供了完整的可編譯示例!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.