我想用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;
}
当我输入say(textToPrint);我想只打印textToPrint
答案 0 :(得分:1)
由于永远不会分配textToPrint
,因此您的代码会测试命令是否为&#34;说();&#34;,在这种情况下,输出一个空行。
为了使其工作,您需要显式解析您的命令。有很多方法可以做到这一点,但一个简单的方法是:
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;
}