【问题标题】:my own print command in c++我自己在 C++ 中的打印命令
【发布时间】:2015-05-06 23:54:22
【问题描述】:

我想用 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

【问题讨论】:

  • 但我的代码不起作用不起作用是什么意思?
  • cout 不打印 textToPrint
  • 所以你想让你的程序神奇地匹配一个表达式并将正确的部分放在 textToPrint 中?
  • 如果你想实现它,这是尝试使用正则表达式。在(command=="say("+textToPrint+");") 行中,编译器没有为textToPrint 分配任何东西。它只是空着。
  • 哦,好的,我明白了,但是如何将 textToPrint 设置为来自用户输入的文本?

标签: c++ printing command cout


【解决方案1】:

由于从未分配过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;
}

【讨论】:

  • textToPrint 从未被赋值。
  • 看来他在没有任务的情况下也能正常工作:)
  • 已修复...如果一直打印空行会感觉不太完整 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多