【问题标题】:instantiating a new object in cpp在 cpp 中实例化一个新对象
【发布时间】:2016-01-17 13:38:42
【问题描述】:

我有 3 个名为 Starter、Pizza 和 Dessert 的类,它们在创建对象时接受可变数量的字符串输入,例如,

//pizza takes 2 inputs
Pizza p("margarita","large size");

//starter takes 3 inputs
Starter s("ribs","bbq sauce","small size");

但我想使用函数 add() 创建一个 new 对象,该函数接受一个字符串并将其与类匹配以创建一个新对象。例如

add(string type)
{
   if(type == "Pizza")
   {
     Pizza *p = new Pizza();
   }

   else if(type == "Starter ")
   {
     Starter *p = new Starter ();
   }
}

现在我的问题是,如何以用户友好的方式为类提供输入?通过用户友好,我认为用户可以在一行中编写一个类的所有输入,而不是使用 cin 来获取每个输入。

假设我们要买披萨,那么我不想要什么,

cout<<"What type of pizza";
cin>>*input* <<endl;
cout<<"What size";
cin>>*input* <<endl;

我想将所有输入写在一行中,例如,

输入“玛格丽塔”,“大”

【问题讨论】:

  • 您想完全从标准输入获取输入吗?不是来自文件或其他东西?
  • 这将是一个简单的解析。使用getline()
  • 目前我正在使用 getline 分别获取每个输入,我可以使用一个 getline() 将两个输入一起获取吗? @MubashirHanif
  • 是的,我只想从标准输入而不是任何文件中获取用户输入。 @maxteneff
  • getline() 为您提供流中的完整行,因此只要用户输入完整的行作为输入,它就会正常工作.. 但您必须确保用户输入每个一切都成一条线。一旦你有一行说用户输入"margarita","large",如果你要求用户通过在他的输入"margarita" "large"中放置空格来格式化输入,那么你必须在,的基础上进行tockenize,然后使用@MuratKarakus在下面回答,这对你很有用。 @SafwanUllKarim

标签: c++ class constructor new-operator dynamic-allocation


【解决方案1】:

感谢@MuratKarakus。只是扩展他的答案以支持这种类型的输入"margarita","large"

// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);

std::replace( order.begin(), order.end(), ',', ' '); // this'll replace all ',' with space

// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
is >> size;    

--------更新

下面的代码是支持"1/2 margarita 1/2 bbq delux", "large"这样的输入

// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);
std::replace( order.begin(), order.end(), ' ', '-'); // this'll replace all space with '-'
std::replace( order.begin(), order.end(), ',', ' '); // this'll replace all ',' with space
// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
std::replace( meal.begin(), meal.end(), '-', ' '); // this'll replace all '-' with space

is >> size;    

【讨论】:

  • 代码有效,但在您的替换中,有没有办法摆脱空间?因为我还想输入“1/2 margarita 1/2 bbq delux”、“large”@MubashirHanif
  • @SafwanUllKarim 非常适合一个完整的解决方案,你应该给我一个完整的用户输入格式.. 对于输入"1/2 margarita 1/2 bbq delux", "large" 这样你可能想要做圆顶的事情线 2 方式替换首先replace所有具有已知字符的空格..说. or -然后使用流来取回部分输入并相应地解析它们..我正在更新我的答案以支持您当前的输入规范
  • 再次感谢!你是一个很大的帮助@MubashirHanif
  • @SafwanUllKarim 提到不是老兄,这是我们的责任:D
【解决方案2】:
// Read complete string.
// Eg. margarita large
string order;
getline(cin, order);

// It automatically parses string based on space
istringstream is(order);
string meal, size;
is >> meal;
is >> size;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    相关资源
    最近更新 更多