error: expected ‘;’ before ‘generationString’

error: expected ‘;’ before ‘generationString’

我目前正在尝试解决我在使用此代码时遇到的一些问题,无法真正弄清楚为什么我会收到这 2 个错误。 我试图查看是否有东西没有关闭,但似乎并非如此,可能是“:”之间距离的原因? 我现在正在抓救命稻草..

main.cpp:30:38: error: expected ‘;’ before ‘generationString’
cout << "Generation " << x << ": " generationString << endl;

main.cpp:54:40: error: expected ‘;’ before ‘generationString’
cout << "Generation " << x++ << ": " generationString << endl;

尝试编译此代码时:

#include <iostream>

using namespace std;

string
initString ()
{
}

int
calculateScore (string guess, string target)
{
}

string
mutate (string mutationString)
{
}


int
main ()
{
  string targetString = "METHINKS IT IS LIKE A WEASEL";
  string generationString = initString ();
  string currentString = generationString;

  int score = calculateScore (currentString, targetString);
  int x = 0;
  cout << "Generation " << x << ": " generationString << endl;
  do
    {
      for (int i = 0; i < 100; i++)
    {
      string newCopy = generationString;
      newCopy = mutate (newCopy);
      int copyScore = calculateScore (newCopy, targetString);

      if (copyScore > score)
        {
      currentString = newCopy;
      score = copyScore;
      if (copyScore == targetString.length ())
    {
      break;
    }

    }
}
  generationString = currentString;

     }
  while (score < targetString.length ());
  cout << "Generation " << x++ << ": " generationString << endl;
  return 0;
  }

您缺少 <<

cout << "Generation " << x << ": " generationString << endl;

应该是

cout << "Generation " << x << ": " << generationString << endl;

同样适用于

cout << "Generation " << x++ << ": " generationString << endl;

应该是

cout << "Generation " << x++ << ": " << generationString << endl;

您可能在

行中遗漏了一个 <<
cout << "Generation " << x << ": " generationString << endl;

给你

": " generationString

应该是

": " << generationString

C++ 可以连接文字字符串,但不能将文字字符串与其他任何内容(如 std::strings)连接。所以例如这会起作用

cout << "Generation " << x << ": " "METHINKS IT IS LIKE A WEASEL" << endl;