我自己的 C++ 打印命令

my own print command in c++

我想用 C++ 创建自己的打印命令,但我的代码不起作用。我必须做什么?

int main()
{

string command;
string textToPrint;
main:

std::cout <<"> ";
std::cin >> command;


if(command=="say("+textToPrint+");") {
    std::cout<< textToPrint << endl;    
}

system("echo.");
goto main;
return 0;

}

When I type say(textToPrint); i want to print only textToPrint

由于从未分配 textToPrint,您的代码会测试命令是否为 "say();",在这种情况下,输出一个空行。
为了使其工作,您需要显式解析您的命令。有很多方法可以做到这一点,但一个简单的方法是:

int main()
{
  string command;
  string textToPrint;

  string commandPrefix = "say(";     
  string commandSuffix = ");";

  while (true) {
    std::cout <<"> ";
    std::cin >> command;

    // see if the command starts with "say("
    auto prefixIdx = command.find(commandPrefix);
    if (0 != prefixIdx) continue;

    // see if the command ends with ");"
    auto suffixIdx = command.rfind(commandSuffix);
    auto expectedSuffixIdx = command.size() - commandSuffix.size();
    if (expectedSuffixIdx != suffixIdx) continue;

    auto textToPrintLength = expectedSuffixIdx - commandPrefix.size();
    textToPrint = command.substr(commandPrefix.size(), textToPrintLength);
    std::cout<< textToPrint << std::endl;    
  }
  return 0;
}