检查c++数组中的hashtag

Checking for a hashtag in c++ array

本文关键字:hashtag 数组 c++ 检查      更新时间:2023-10-16

我正试图计算我的tweet数组中有多少个特定的标签。我得到了疯狂的数字。这是我的代码:

// returns the number of tweets with the given hashtag
int MicroBlog::GetNumHashtag(const string Hashtag)
{
   string Choice;
   int NumHashtag;
   cout << "Which hashtag would you like to check for in the tweets? " << endl;
   cin >> Choice;
   cout << "The hashtag you have chosen is: " << Choice << endl;
   for (int i = 0; i < MAX_TWEETS; i++)
   {
      if (blog[i].GetHashtag() == Choice)
         NumHashtag++;
   }
   cout << "There are " << NumHashtag << " hashtags in the blog. " << endl;
   return NumHashtag;
}

这一行:

int NumHashtag;

导致未定义行为

包括位于分配给NumHashtag的内存对象中的随机数。您唯一要做的就是初始化对象:

int NumHashtag = 0;