【问题标题】:How can I add numbers before my output here?如何在我的输出之前添加数字?
【发布时间】:2017-02-23 21:16:17
【问题描述】:

我正在为我的班级编写 C++ 程序,但我不确定规范。我想在字符串 orderCode 的输出之前添加数字,但不确定如何执行此操作。例如,输入“BF12”的输出将是“12 Black Forest cakes”。我试图将蛋糕的数量和数量包含在一个字符串变量中。谁能给我一些指示?任何事情都会非常感激。

这是我的代码:

#include <iostream>
using namespace std;

int main() {

string orderCode;
string repeat = "y";
while ("y" == repeat) {

cout << "\nWelcome to the Great Cake company!\n";
cout << "\nEnter the cake order code: ";
cin >> orderCode;

int quantity = orderCode.length() - 1;


if (orderCode == "BF2")
{ (cout << orderCode.substr(quantity) << " Black Forest cakes");
}

if (orderCode == "CC")
  { (cout << "Carrot cakes");
}

  if (orderCode == "CM")
     { (cout << "Chocolate Mint cakes");
}

  if (orderCode == "DF")
     { (cout << "Devil's Food cakes");
}

  if (orderCode == "GC")
     { (cout << "German Chocolate cakes");
}

  if (orderCode == "PC")
     { (cout << "Pumpkin Cheesecakes");
}

  if (orderCode == "RC")
     { (cout << "Rum cakes");
}

  if (orderCode == "T")
     { (cout << "Tiramisu cakes");
}

cout << "\nOrder more? (y/n) ";
cin >> repeat;
}


return 0;
}

【问题讨论】:

  • 据我所知,您不是在问如何“添加数字”。您正在询问如何根据某些预定义格式解析输入。那是一锅完全不同的鱼。
  • 是的,这就是我想要的。我不知道如何准确地表达它。任何指针?感谢您的回复。
  • 这些数字是否来自任何地方?根据问题,我猜订单代码...
  • @joegame 首先,您编写一个非常小的 程序,以便练习如何将两个单独的项目输入到两个单独的变量中。您不需要您发布的所有代码 to do this。然后,当您知道如何执行此操作时,然后您将其添加到更大的程序中。试图在不知道如何做简单的事情的情况下一次性编写整个程序不是编写程序的方式。
  • 您可以使用函数strcspn()查找字符串中的第一个数字字符。

标签: c++ string variables numbers output


【解决方案1】:

您想解析用户输入,假设数字总是在字母之后并且假设数字是小数(因此不将 ABCDEF 计为数字的一部分)。

string orderCode = "BF12";
size_t last_index = orderCode.find_last_not_of("0123456789");
string result = orderCode.substr(last_index + 1);
result += " Black Forest cakes";
cout << result << endl;

同时,对于您的开关盒,您仍然需要擦除输入的数字部分。

orderCode.erase(last_index+1);

然后您可以与orderCode进行比较

【讨论】:

    【解决方案2】:

    您需要省略 BF 并提取数字。由于 BF 的长度为 2,因此您需要打印其余部分:

    cout << orderCode.substr(2, quantity) << " Black Forest cakes"
    

    同时,您的开关盒没有任何意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2019-11-12
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      相关资源
      最近更新 更多